u936293
u936293

Reputation: 16224

context.drawImage behaving weirdly

I have:

<canvas id='canvas' width="300" height="409" style="border:2px solid darkblue" >
</canvas>

And then:

<script type="text/javascript">
  var canvas = document.getElementById('canvas');
  var context = canvas.getContext('2d');
  var image = new Image();
  image.src = 'http://4.bp.blogspot.com/...-21+Kingfisher.JPG';
  alert(image.src);
  context.drawImage(image, 0, 0, 300, 400);
</script>

In IE 10, the image is painted as "to be expected". However, when I remove that alert statement, the picture is not painted!

In Chrome, no image is painted on my local PC, whether with or without the alert statement.

What could be happening? The fiddle is here

Upvotes: 2

Views: 105

Answers (1)

user1693593
user1693593

Reputation:

That is because loading images is an asynchronous operation. The alert call helps the browser to wait a bit so the image loading can finish. Therefor the image will be available at drawImage that follows.

The correct way to implement this is to use the code this way:

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var image = new Image(); //document.createElement('img'); for Chrome due to issue

// add a onload handler that gets called when image is ready
image.onload = function () {
    context.drawImage(this, 0, 0, 300, 400);
}

// set source last so onload gets properly initialized
image.src = 'http://4.bp.blogspot.com/...-21+Kingfisher.JPG';

The draw operation inside the callback for onload could just as easily have been a function call:

image.onload = nextStep;
// ...

function nextStep() {
    /// draw image and other things...
}

Upvotes: 4

Related Questions