简体   繁体   English

为什么HTML 5 Canvas无法绘制图像内容?

[英]Why HTML 5 Canvas Does Not Draw Image Content?

I'm trying to generate an image from a HTML 5 Canvas, but it's not "rendering" image content from the canvas. 我正在尝试从HTML 5 Canvas生成图像,但不是从画布“渲染”图像内容。

Here is the code: http://jsfiddle.net/9kQPk/ 这是代码: http : //jsfiddle.net/9kQPk/

It's supposed to be simple, I create a canvas, set a few things and a image using "drawImage" function, but when I try to generate an img html component, the image from canvas does not appear... Here is the JS: 它应该很简单,我创建了一个画布,使用“ drawImage”函数设置了一些东西和一个图像,但是当我尝试生成一个img html组件时,来自画布的图像不会出现...这是JS:

$('#drawing').css("visibility", "visible");         
var drawing = document.getElementById("drawing");
var con = drawing.getContext("2d");         
drawing.setAttribute("width", 500);
drawing.setAttribute("height", 200);
con.fillStyle = "#FF0000";
con.fillRect(0, 0, 500, 200);                                           
var img = new Image();
img.src = "http://www.deque.com/wbcntnt928/wp-content/dquploads/jquery_logo.png";
img.onload = function() {                
    con.drawImage(img, 0, 0, 250, 250);
};

//Generate Image
var drawing = document.getElementById("drawing");
var dataURL = drawing.toDataURL();
document.getElementById("result").src = dataURL;

Thanks! 谢谢!

You're getting content of the canvas before you draw the image, put the generate image code in the onload function 在绘制图像之前,先获取画布的内容,然后将生成图像代码放入onload函数中

var img = new Image();
img.onload = function() {                
    con.drawImage(img, 0, 0, 250, 250);
    //Generate Image
    var drawing = document.getElementById("drawing");
    var dataURL = drawing.toDataURL();
    document.getElementById("result").src = dataURL;
};
img.src = "http://www.deque.com/wbcntnt928/wp-content/dquploads/jquery_logo.png";

note that the image must be of the same origin as the webpage drawing it to be able to save it. 请注意,图片必须与绘图的网页具有相同的来源才能保存。

DEMO 演示
Code

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM