英文:
canvas.toDataURL("image/jpeg") can't be used in .drawImage()
问题
我正在尝试使用 canvas.toDataURL("image/jpeg")
来捕获画布屏幕,然后在 ctx.drawImage();
中使用它,但出现错误 "Uncaught TypeError",表示不支持该图像格式。我应该在 .toDataURL()
中使用哪种格式来修复它?
英文:
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
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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
<!-- language: lang-html -->
<canvas id="canvas"></canvas>
<!-- end snippet -->
I use in .toDataURL()
to fix it?
答案1
得分: 0
The issue is that test
is a string.
问题在于 test
是一个字符串。
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>
英文:
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:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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
<!-- language: lang-html -->
<canvas id="canvas"></canvas>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论