[英]Save HTML5 canvas with images as an image
I'm trying to save a canvas with images to PNG, but when I try this: 我正在尝试将包含图像的画布保存为PNG,但是当我尝试这样做时:
var myCanvas = document.getElementById("myCanvas");
var img = document.createElement('img');
var ctx = myCanvas.getContext ? myCanvas.getContext('2d') : null;
img.src = 'image.png';
img.onload = function () {
ctx.drawImage(img, 0, 0, myCanvas.width, myCanvas.height);
}
var data = myCanvas.toDataURL("image/png");
if (!window.open(data)) {
document.location.href = data;
}
I only get a blank transparent image without the image. 我只得到一个空白的透明图像而没有该图像。 What am I doing wrong?
我究竟做错了什么?
You need to put the window.open
call in the load handler since this happens asynchronously . 您需要将
window.open
调用放入加载处理程序中,因为这是异步发生的。
img.onload = function () {
ctx.drawImage(img, 0, 0, myCanvas.width, myCanvas.height);
var data = myCanvas.toDataURL("image/png");
if (!window.open(data)) {
document.location.href = data;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.