Canvas.drawImage 不工作
Canvas.drawImage not working
我知道这个问题已经被问过很多次了,但我不知道我做错了什么
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);
}
<div id="preview"></div>
<input type="file" onchange="handleFiles(this.files)">
<canvas id="myCanvas"></canvas>
应该是
img.onload = function(){drawImage(img)};
如果没有方法参数你可以调用
img.onload = drawImage;
而不是
img.onload = drawImage()// not correct
语法是
x.onload = funcRef;//reference
您应该分配一个函数引用。如果您分配 drawImage(img)
,那么 drawImage(img)
的 return 值将分配给 onload 函数
我知道这个问题已经被问过很多次了,但我不知道我做错了什么
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);
}
<div id="preview"></div>
<input type="file" onchange="handleFiles(this.files)">
<canvas id="myCanvas"></canvas>
应该是
img.onload = function(){drawImage(img)};
如果没有方法参数你可以调用
img.onload = drawImage;
而不是
img.onload = drawImage()// not correct
语法是
x.onload = funcRef;//reference
您应该分配一个函数引用。如果您分配 drawImage(img)
,那么 drawImage(img)
的 return 值将分配给 onload 函数