Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript create blank placeholder image dynamically

I need to dynamically create a blank placeholder image in JavaScript, width and height unknown until runtime.

The generated image should be fully transparent with the dimensions given in PNG format.

It is important that the actual generated image itself has the dimensions given, merely setting the width and height attributes of the generated img tag is not sufficient.

I need something like this:

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)

How can I do this?

PS I know I could probably find an online service to do this for me, but I want to avoid the overhead of an HTTP call to get the image.

like image 996
danday74 Avatar asked Jun 16 '26 22:06

danday74


1 Answers

You can use an HTML Canvas and fill it with a transparent rectangle, then convert it to a data url and attach it to an Image element.

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
#img1 {
  border: 1px solid red;
}

#img2 {
  border: 1px solid blue;
}
<img id="img1">
<img id="img2">

<div>Right click an image above and select Save image as...</div>
like image 146
skara9 Avatar answered Jun 18 '26 14:06

skara9



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!