我一直在尝试从画布上获取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);

最佳答案

您将得到一个空的画布,因为您的代码没有等待图像正确加载。图像加载是异步的。

您还假设图像1完成后,两个图像均已加载。


您需要等待两个图像都加载
绘制图像后,从加载处理程序内部调用toDataURL()(或调用另一个函数)。
您正在尝试从可能尚未加载的图像设置画布的高度。加载图像时进行设置
您可能会在此处触发CORS限制,请确保图像与页面位于同一服务器上,或者该服务器允许跨域使用。否则,将引发安全错误。




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";

10-05 23:47