-1

const canvas = document.createElement('canvas');
canvas.width = 500;
canvas.height = 500;
canvas.style.backgroundColor = 'lightgreen';
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
let image = document.createElement('img');
image.src = 'https://www.pngplay.com/wp-content/uploads/5/Alphabet-C-Transparent-File.png';
document.body.appendChild(image);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(image, 0, 0, 500, 500);
ctx.fillRect(100, 100, 50, 50);
canvas {
  border: 1px solid black;
}

If I use ctx.drawImage(...) with the canvas created in js, it will not work.
If I use fillRect(...), it does draw rectangle as intended.
At least in Vscode. It doesn't draw rectangle in this code snippet thing. I cannot figure out why this is.
Does anyone know why?

lcm5506
  • 11
  • 1
  • 4

1 Answers1

0

You need to wait until the image hs loaded before drawing it on the canvas.

This snippet adds an event listener to the img element and draws it when the load event fires.

const canvas = document.createElement('canvas');
canvas.width = 500;
canvas.height = 500;
canvas.style.backgroundColor = 'lightgreen';
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
let image = document.createElement('img');
image.src = 'https://www.pngplay.com/wp-content/uploads/5/Alphabet-C-Transparent-File.png';
document.body.appendChild(image);
ctx.clearRect(0, 0, canvas.width, canvas.height);
image.addEventListener('load', function() {
  ctx.drawImage(image, 0, 0, 500, 500);
  ctx.fillRect(100, 100, 50, 50);
});
canvas {
  border: 1px solid black;
}
A Haworth
  • 30,908
  • 4
  • 11
  • 14