JavaScript 动态创建空白占位符图像

dan*_*y74 7 javascript image

我需要在 JavaScript 中动态创建一个空白占位符图像,宽度和高度在运行时之前未知。

生成的图像应完全透明,尺寸以 PNG 格式给出。

重要的是,实际生成的图像本身具有给定的尺寸,仅设置生成的 img 标签的宽度和高度属性是不够的。

我需要这样的东西:

const createImage = (width, height) => {
  const img = new Image()
  // img must have width and height in px as specified (see above proviso)
  // img must also be a transparent PNG
  return img
}

const img1 = createImage(100, 100)
const img2 = createImage(640, 480)
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

PS 我知道我可能会找到一个在线服务来为我执行此操作,但我想避免 HTTP 调用来获取图像的开销。

ska*_*ra9 10

您可以使用 HTML Canvas 并用透明矩形填充它,然后将其转换为数据 url 并将其附加到 Image 元素。

const createImage = (width, height) => {

  const canvas = document.createElement('canvas')
  canvas.width = width
  canvas.height = height
  
  const ctx = canvas.getContext('2d')
  ctx.fillStyle = 'rgba(0, 0, 0, 0)'
  ctx.fillRect(0, 0, width, height)

  const img = new Image(width, height)
  img.src = canvas.toDataURL()

  return img
}

const img1El = document.getElementById('img1')
const img2El = document.getElementById('img2')
const img1 = createImage(100, 50)
const img2 = createImage(20, 50)
img1El.src = img1.src
img2El.src = img2.src
Run Code Online (Sandbox Code Playgroud)
#img1 {
  border: 1px solid red;
}

#img2 {
  border: 1px solid blue;
}
Run Code Online (Sandbox Code Playgroud)
<img id="img1">
<img id="img2">

<div>Right click an image above and select Save image as...</div>
Run Code Online (Sandbox Code Playgroud)