javascript draw a image on canvas

前端 未结 2 579
闹比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:47

    The image is loading asynchronously. This code will work:

    JavaScript:

    function setup(){
        var canvas = document.getElementById('myCanvas');
        var ctx = canvas.getContext('2d');
        canvas.width = 800;
        canvas.height = 600;
        var image = new Image();
        image.onload = function () {
            ctx.drawImage(image,5,5);
        };
        image.src = 'a.png';
    }
    window.onload = setup;
    
    0 讨论(0)
  • 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.

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