context.drawImage表现得很奇怪 [英] context.drawImage behaving weirdly

查看:664
本文介绍了context.drawImage表现得很奇怪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有:

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

这篇关于context.drawImage表现得很奇怪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆