Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript draw a image on canvas

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:

<body>
<canvas id = "my_canvas"></canvas>
<script>
function setup(){
    var canvas = document.getElementById('my_canvas');
    var ctx = canvas.getContext('2d');
    canvas.width = 800;
    canvas.height = 600;
    var image = new Image();
    image.src = 'a.png';
    ctx.drawImage(image,5,5);
};
window.onload = setup;
setup();

</script>

The question is, if I put a line of code setup(); at end then the image is correctly draw, I don't know why.

Thanks.

like image 763
changbenny Avatar asked Oct 19 '13 20:10

changbenny


2 Answers

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.

like image 172
6502 Avatar answered Oct 08 '22 20:10

6502


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;
like image 22
Xitalogy Avatar answered Oct 08 '22 19:10

Xitalogy