简体   繁体   中英

JS drawImage broken

The image is in the same directory and everything, I can't seem to get it to work.

<body>
<center>
<canvas id='scrn' width='100' height='100'/>
</center>
<script>
function draw() {
var cv = document.getElementById('scrn').getContext('2d');
var img = document.getElementById('image');
cv.drawImage(img,10,10 10, 10,);
}
draw();
</script>
<image id='image' src='test.jpg'/>
</body>

The image shows up in the <image> tag but not in the canvas. Why is that?

You need to use a callback so that boot() is called only after the image loads. For example:

document.getElementById("image").onload = boot
var canvas = document.getElementById('scrn'); // get your canvas
    if (canvas) {
      var context = canvas.getContext('2d'); // get canvas context
      var img = document.getElementById('image'); // get image
      if (context && img) { // make sure context and img exists
        img.onload = () => { // call drawImage when img has finished loading
          context.drawImage(img,10,10 10, 10,);
        }
      }
    }

I would advise using let and const over var. For future note, always use drawImage inside an image's onload callback because that ensures the image which you wish to draw has successfully loaded.

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