“canvas.toDataURL("image/jpeg")” 不能在 .drawImage() 中使用。

huangapple go评论59阅读模式
英文:

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(&quot;canvas&quot;);
const ctx = canvas.getContext(&quot;2d&quot;);

ctx.beginPath();
ctx.rect(0,0, 100, 100);
ctx.fill();

const test = canvas.toDataURL(&quot;image/jpeg&quot;);

ctx.fillStyle = &quot;white&quot;;
ctx.beginPath();
ctx.rect(0,0, 100, 100);
ctx.fill();

ctx.drawImage(test, 0, 0); //Uncaught TypeError

<!-- language: lang-html -->

&lt;canvas id=&quot;canvas&quot;&gt;&lt;/canvas&gt;

<!-- 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(&#39;load&#39;, () =&gt; {
    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(&#39;canvas&#39;)
const ctx = canvas.getContext(&#39;2d&#39;)

ctx.beginPath()
ctx.rect(0, 0, 100, 100)
ctx.fill()

const test = canvas.toDataURL(&#39;image/jpeg&#39;)

ctx.fillStyle = &#39;white&#39;
ctx.beginPath()
ctx.rect(0, 0, 100, 100)
ctx.fill()

const image = new Image()
image.addEventListener(&#39;load&#39;, () =&gt; {
  ctx.drawImage(image, 0, 0)
})
image.src = test

<!-- language: lang-html -->

&lt;canvas id=&quot;canvas&quot;&gt;&lt;/canvas&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月21日 02:11:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76296720.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定