简体   繁体   中英

Drawing an image onto a canvas in Javascript

I'm looking to draw an image onto a canvas for my HTML page using a separate Javascript file. The HTML I have thus far is fine, my problem seems to lie within the script. This is what I have currently:

    function doFirst(){
    var x = document.getElementById('canvas');
    canvas = x.getContext('2d');

    var pic = new image();
    pic.src="http://i1273.photobucket.com/albums/y418/Cloudtwonj/Backgroundtest_zps2a6a6b51.jpeg";
    pic.addEventListener("load", function(){canvas.drawImage(pic,0,0,x.width,x.height)}, false);
}
window.addEventListener("load", doFirst, false);

Can anyone tell me what I might have done wrong or forgot?

The constructor is Image , not image - capitalization matters!

var pic = new Image();

  function doFirst() { var x = document.getElementById('canvas'); canvas = x.getContext('2d'); var pic = new Image(); pic.src = "http://i1273.photobucket.com/albums/y418/Cloudtwonj/Backgroundtest_zps2a6a6b51.jpeg"; pic.addEventListener("load", function() { canvas.drawImage(pic, 0, 0, x.width, x.height) }, false); } window.addEventListener("load", doFirst, false); 
 <canvas id="canvas"></canvas> 

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