Canvas.drawImage不起作用

时间:2016-10-17 10:57:26

标签: javascript html5 html5-canvas drawimage

我知道很多次都会问这个问题,但我无法弄清楚我做错了什么



var canvas = document.getElementById('myCanvas');

function handleFiles(files) {
  var preview = document.getElementById('preview');
  for (var i = 0; i < files.length; i++) {
    var file = files[i];
    var imageType = /^image\//;

    if (!imageType.test(file.type)) {
      continue;
    }

    var img = document.createElement("img");
    img.classList.add("obj");
    img.src = URL.createObjectURL(file);
    preview.appendChild(img); // Assuming that "preview" is the div output where the content will be displayed.

    img.onload = drawImage(img);

  }
}
var drawImage = function(img) {
  var ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0);

}
&#13;
<div id="preview"></div>
<input type="file" onchange="handleFiles(this.files)">
<canvas id="myCanvas"></canvas>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

DEMO

应该是

img.onload = function(){drawImage(img)};

如果没有方法参数,你可以调用

img.onload = drawImage;

而不是

 img.onload = drawImage()// not correct

语法是

x.onload = funcRef;//reference

你应该分配一个函数参考。如果你指定drawImage(img),那么drawImage(img)的返回值将被分配给onload函数