我一直试图从画布中获取Base64字符串。但是我不能。 以下代码不执行任何操作。应该将图像插入document.body。另一方面,我试图获得base64字符串并转换图像。但我再也不能。
我该怎么办?
http://jsfiddle.net/27hdp4y6/1/
var image1 = new Image();
image1.src = "http://www.w3.org/html/logo/downloads/HTML5_Logo_128.png";
var image2 = new Image();
image2.src = "http://prismitsolutions.com/images/icons/css3.png";
var canvas = document.createElement('canvas');
canvas.width = 220;
canvas.height= image1.height;
var context = canvas.getContext("2d");
image1.onload = function() {
context.drawImage(image1, 0, 0);
context.drawImage(image2, 80, 0);
};
var base64 = canvas.toDataURL('image/png');
var img = document.createElement('img');
img.src=base64;
document.body.appendChild(img);
//document.body.appendChild(canvas);
答案 0 :(得分:1)
您将获得一个空白画布,因为您的代码不会等待图像正确加载。图像加载是异步的。
您还假设在图像1完成时已加载两个图像。
toDataURL()
(或调用其他函数)。
var image1 = new Image();
var image2 = new Image();
var count = 2; // two images to load, for more use an array instead
image1.onload = image2.onload = function() {
count--;
if (!count) {
var canvas = document.createElement('canvas');
canvas.width = 220;
canvas.height = image1.height;
var context = canvas.getContext("2d");
context.drawImage(image1, 0, 0);
context.drawImage(image2, 80, 0);
// the data-uri, use f.ex. a callback function with this as
// argument to process it further (not shown here)
var base64 = canvas.toDataURL('image/png');
var img = document.createElement('img'); // ideally, use a handler here too
img.src = base64;
document.body.appendChild(img);
}
};
// we need cross-origin in this case/demo as images exists on a different server
// imgur.com allow using cross-origin, not all servers do though...
image1.crossOrigin = image2.crossOrigin = "anonymous";
// set sources after handlers are defined
image2.src = "http://i.imgur.com/bk0rvnj.png";
image1.src = "http://i.imgur.com/wlPnCM1.png";

答案 1 :(得分:0)
使用appendChild()cf。http://jsfiddle.net/27hdp4y6/1/ 只需添加:
...
document.body.appendChild(canvas);
var context = canvas.getContext("2d");
...
答案 2 :(得分:0)
您应该将画布附加到DOM:
document.body.appendChild(canvas);