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 行为怪异
基础教程推荐
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 直接将值设置为滑块 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01