在 JavaScript 中从 URL 加载图像
 
今天的文章将介绍如何在 JavaScript 中从指定的 URL 加载图像。
在 JavaScript 中从 URL 加载图像
图片标签的 HTML 元素在文档中嵌入了一张照片/图片。src 属性携带指向你需要嵌入的照片/图像的方向。
Src 是图像元素所需的图像的 URL。
在支持 srcset 的浏览器中,src 被视为具有 1x 像素密度描述符的候选图像,除非具有该像素密度描述符的图像已经在 srcset 中定义或 srcset 包含 w描述符。
以下是网络上最常用的图像文件格式列表。
- APNG- 动画便携式网络图形
- GIF- 图形交换格式
- PNG- 便携式网络图形
- WebP- 网络图片格式
- SVG- 可缩放矢量图形
- JPEG- 联合图像专家组图像
- AVIF-- AV1图像文件格式
推荐使用 WebP 和 AVIF 等格式,因为它们对于静态和动画图像的效果都比 PNG、JPEG 和 GIF 好得多。WebP 在 Safari 中得到广泛支持,而 AVIF 在 Safari 中不受支持。
对于必须以各种尺寸准确绘制的图像,SVG 仍然是推荐的格式。你可以在 image 的文档中找到更多信息。
让我们通过以下示例来理解它。
<input type="text" value="helloworld" id="imageName"/>
<input type="button" id="insert-btn" value="Insert" />
document.getElementById('insert-btn').onclick = function() {
  const val = document.getElementById('imageName').value;
  const src = 'https://google.com/images/' + val + '.png';
  let imgTag = document.createElement('img');
  imgTag.src = src;
  document.body.appendChild(imgTag);
}
我们在上面的示例中定义了输入元素,用户可以在其中动态输入特定图像的值。你可以提供选择下拉菜单而不是输入选项,并根据用户选择更改图像。
一旦用户点击按钮,获取用户选择并为文档创建 img 元素。将图像的位置或路径设置为 src 属性,并将图像元素作为子元素附加到现有 DOM。
Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.
LinkedIn