使用此代码,当 imageUpdated 为 true 时,我尝试使用绘制的图像更新 Canvas 。
我使用时间标签,因此图像不会从浏览器缓存加载。
但是当我使用时间标签时, Canvas 保持空白。
它无需时间标签即可工作。
var imageUpdated = true;
if(imageUpdated)
{
imageUpdated = false;
var heightImg = new Image;
heightImg.src = '/path/to/image.png?' + new Date().getTime().toString();
this.canvas = $('<canvas />')[0];
this.canvas.width = this.width;
this.canvas.height = this.height;
this.canvas.getContext('2d').drawImage(heightImg, 0, 0, this.width, this.height);
}
/*rest of event happens here*/
谢谢!
最佳答案
可能是因为您在加载图像之前绘制图像。 我想这也是它在没有时间标签的情况下工作的原因,它已经在缓存中,所以可以立即绘制。
解决方案是在加载图像后进行绘制。因此,在图像上添加一个事件监听器:
image.addEventListener('load', callback);
在回调中,在 Canvas 上绘制图像。
例如:
// add eventlistener
heightImg.addEventListener('load', function(e) {
var width = heightImg.width;
var height = heightImg.height;
var canvas = document.querySelector('canvas');
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(heightImg, 0, 0, width, height);
});
// trigger the loading
heightImg.src = url + '?time=' + new Date().getTime().toString();
还有一个 Fiddle
关于javascript - 当 image.src 有时间标签时更新 Canvas 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37527577/