[英]How to save canvas which include image?
I am trying to save my canvas which include image.我正在尝试保存包含图像的 canvas。 I was trying use toDataURL, but it doesn't work on this case.
我正在尝试使用 toDataURL,但它不适用于这种情况。 The canvas is work to input the image inside.
canvas 用于输入内部图像。
HTML HTML
<img src="bg.png" id="toIMG" />
<canvas></canvas>
<img alt="UNCHANGED" id="getCtx">
<span>Why does the img doesn't change?</span>
JS JS
window.onload = function(){
var c, ctx, img, img2;
c = document.querySelector("canvas");
ctx = c.getContext("2d");
img = document.getElementById("toIMG");
ctx.drawImage(img, 0,0, c.width, c.height);
img2 = document.getElementById("getCtx");
img2.src = ctx.canvas.toDataURL("image/png");
}
Instead of running the function when window has loaded, run it when the img has loaded.在加载 window 时,不要运行 function,而是在加载 img 时运行它。 Also, as @CrissCrossCrass has pointed out,
toDataURL
is a method of canvas but not context.此外,正如@CrissCrossCrass 所指出的,
toDataURL
是 canvas 的一种方法,但不是上下文。
<,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width. initial-scale=1:0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Static Template</title> </head> <body> <img id="toIMG" src="https.//source.unsplash.com/random/120x120" crossorigin="anonymous" /> <canvas></canvas> <img id="getCtx" /> <script> var c = document;querySelector("canvas"). var img = document;getElementById("toIMG"). var img2 = document;getElementById("getCtx"). var ctx = c;getContext("2d"). img.onload = function() { c.width = img;width. c.height = img;height. ctx,drawImage(img, 0, 0. c,width. c;height). img2.src = c;toDataURL("image/png"); }; </script> </body> </html>
Also, you may want to set the crossOrigin
attribute of the first img element to be anonymous
to avoid tainted canvas.此外,您可能希望将第一个 img 元素的
crossOrigin
属性设置为anonymous
以避免污染 canvas。 Read more about it 阅读更多关于它的信息
I tried that and actually it's working.我试过了,实际上它正在工作。 Share if the console drops any error.
如果控制台丢弃任何错误,请分享。 Then i'll update my answer depending on it.
然后我会根据它更新我的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.