context.drawImage behaving weirdly(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 行为怪异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:context.drawImage 行为怪异


基础教程推荐
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01