HTML5 Canvas - How to draw rectangle over image in canvas

前端 未结 2 1959
误落风尘
误落风尘 2020-12-16 21:37

Actually, I am able to do it using img.onload function. Something I got from \'HTML5 Canvas - How to Draw a line over an image background?\'. But I need to draw

相关标签:
2条回答
  • 2020-12-16 22:14

    Because you are not waiting for the image to load first. In your script add an window.onload()

    <script>
    window.onload = function() {
      var c=document.getElementById("myCanvas");
      var ctx=c.getContext("2d");
      var img=document.getElementById("scream");  
      ctx.drawImage(img,10,10);  
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');
    
      context.beginPath();
      context.rect(188, 50, 200, 100);
      context.fillStyle = 'yellow';
      context.fill();
      context.lineWidth = 7;
      context.strokeStyle = 'black';
      context.stroke();
    }
    </script>
    

    What is happening is it's trying to draw the image before it loaded, doing window.onload will call the code once the entire document is loaded (such as images). Otherwise it may display no image or draw it out of line.

    0 讨论(0)
  • 2020-12-16 22:26

    I tried this same approach of using window.onload() and it worked until I tried it using Microsoft Edge browser. A solution to that which worked for me was to attach an onload handler to the image, such as:

    image.onload = function ()
    {
        context.drawImage(image, 0, 0);
    }
    

    then it worked perfectly.

    0 讨论(0)
提交回复
热议问题