context.drawImage 行为怪异

2022-01-17 00:00:00 canvas javascript html5-canvas

我有:

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

然后:

<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>

在 IE 10 中,图像被绘制为预期".但是,当我删除该警告语句时,图片并未绘制!

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

在 Chrome 中,无论有无警报声明,都不会在我的本地 PC 上绘制任何图像.

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

推荐答案

那是因为加载图片是一个异步操作.警报调用可帮助浏览器稍等片刻,以便完成图像加载.因此,该图像将在随后的 drawImage 中提供.

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';

onload 回调中的绘制操作可以很容易地成为函数调用:

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...
}

相关文章