javascript draw a image on canvas

前端 未结 2 617
闹比i
闹比i 2021-01-19 03:38

I try to build a javascript code, to draw a image on canvas, but I don\'t know where go wrong. That is my code:




        
2条回答
  •  长情又很酷
    2021-01-19 03:58

    The problem is that image is loaded asynchronously, so if you set the source and draw it immediately then the image bits are not yet available and nothing is drawn.

    You have to wait for the image to load before being able to draw it on a canvas.

    Changing the code to

    image.onload = function() {
        ctx.drawImage(image, 5, 5);
    };
    image.src = "a.png";
    

    should work as expected.

提交回复
热议问题