Home > Blockchain >  javascript create blank image dynamically
javascript create blank image dynamically

Time:12-24

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)

Any ideas how to do this? TIA

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.

CodePudding user response:

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(255, 255, 255, 0)";
  ctx.fillRect(0, 0, width, height);

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

  return img;
}

CodePudding user response:

You were close, the first and second arguments of the Image constructor are the width and height:

        const createImage = (width, height) => {
        const img = new Image(width, height)
        return img
        }

        const img1 = createImage(100, 100)
        const img2 = createImage(640, 480)
        document.body.append(img1, img2)

CodePudding user response:


function createImage(width, height) {
  let img = document.createElement('img');
  img.style.minWidth = `${width}px`;
  img.style.minHeight = `${height}px`;
  return img;
}


const img1 = createImage(100, 100)
const img2 = createImage(640, 480)
document.body.appendChild(img1)

  • Related