简体   繁体   中英

Canvas.drawImage not working

I know this question has been asked lot of times, but i am not able to figure out what am i doing wrong

 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> 

DEMO

it should be

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

if there is no method argument you can call

img.onload = drawImage;

instead of

 img.onload = drawImage()// not correct

syntax is

x.onload = funcRef;//reference

you should assign a function reference .if you assign drawImage(img) then return value of drawImage(img) will be assigned to onload function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM