Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

canvas.toDataURL("image/jpeg") can't be used in .drawImage()

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading