在图像加载

时间:2016-01-20 13:03:49

标签: javascript html canvas

我正在尝试创建画布绘图,但是当我使用toDataUrl时,它会返回空的画布文件。

可能是因为在我的图像加载之前触发了toDataUrl,所以如何更改它以便我尝试加载的图像是canvas文件的一部分。               

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var img = new Image();
img.addEventListener("load", function() {
    ctx.drawImage(img, 0, 0, 800, 420);
}, false);
img.src = "images/quizes/sim.png";

var img1 = new Image();
img.addEventListener("load", function() {
    ctx.drawImage(img1, 0, 0, 320, 320);
}, false);
ctx.drawImage(img1, 0, 0, 320, 320);
img1.src = "images/users/alfred.jpg";

var img2 = new Image();
img.addEventListener("load", function() {
    ctx.drawImage(img2, 480, 0, 320, 320);
}, false);
img2.src = "images/users/brynjar.jpg";

var dataURL = canvas.toDataURL();

$.ajax({
    type: "POST",
    url: "script.php",
    data: {
        imgBase64: dataURL
    }
}).done(function(o) {
    console.log('saved');
});

1 个答案:

答案 0 :(得分:1)

使用Promises(大多数IE不支持)

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

function loadImage(image, x, y, width, height) {
  return new Promise(function(resolve, reject) {

    var img = new Image();
    img.onload = function() {
      ctx.drawImage(img, x, y, width, height);
      resolve(image);
    };
    img.onerror = reject;
    img.src = image;
    if (img.complete) img.onload();
  });
}


var img1 = loadImage("images/quizes/sim.png", 0, 0, 800, 420);
var img2 = loadImage("images/users/alfred.jpg", 0, 0, 320, 320);
var img3 = loadImage("images/users/brynjar.jpg", 480, 0, 320, 320);    

Promise.all([img1, img2, img3]).then(function(value) {

  console.log(value);
  var dataURL = canvas.toDataURL();

  $.ajax({
    type: "POST",
    url: "script.php",
    data: {
      imgBase64: dataURL
    }
  }).done(function(o) {
    console.log('saved');
  });
}, function(reason) {
  console.error(reason);
});

如果您需要IE,可以使用PollyFills重新创建支持。其他选择是使用计数器。

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

function loadImage(image, x, y, width, height) {

  var img = new Image();
  img.onload = function() {
    ctx.drawImage(img, x, y, width, height);
    count++;
    if (count === totalCount) {
      allLoaded();
    }
  };
  img.onerror = function() {
    alert("You have a problem");
  };
  img.src = image;
  if (img.complete) img.onload();

}


function allLoaded() {
  var dataURL = canvas.toDataURL();

  $.ajax({
    type: "POST",
    url: "script.php",
    data: {
      imgBase64: dataURL
    }
  }).done(function(o) {
    console.log('saved');
  });
}

var count = 0;
var totalCount = 3;
var img1 = loadImage("images/quizes/sim.png", 0, 0, 800, 420);
var img2 = loadImage("images/users/alfred.jpg", 0, 0, 320, 320);
var img3 = loadImage("images/users/brynjar.jpg", 480, 0, 320, 320);