I am trying to capture a canvas screen using canvas.toDataURL("image/jpeg")
and then use it in ctx.drawImage();
, but it gives the error "Uncaught TypeError" saying that the image format is not supported. Which format do
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.rect(0,0, 100, 100);
ctx.fill();
const test = canvas.toDataURL("image/jpeg");
ctx.fillStyle = "white";
ctx.beginPath();
ctx.rect(0,0, 100, 100);
ctx.fill();
ctx.drawImage(test, 0, 0); //Uncaught TypeError
<canvas id="canvas"></canvas>
I use in .toDataURL()
to fix it?
The issue is that test
is a string.
const image = new Image()
image.addEventListener('load', () => {
ctx.drawImage(image, 0, 0)
})
image.src = test
In context:
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')
ctx.beginPath()
ctx.rect(0, 0, 100, 100)
ctx.fill()
const test = canvas.toDataURL('image/jpeg')
ctx.fillStyle = 'white'
ctx.beginPath()
ctx.rect(0, 0, 100, 100)
ctx.fill()
const image = new Image()
image.addEventListener('load', () => {
ctx.drawImage(image, 0, 0)
})
image.src = test
<canvas id="canvas"></canvas>