javascript - 当 image.src 有时间标签时更新 Canvas 图像

标签 javascript html canvas


使用此代码,当 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/

相关文章:

javascript - 如何在 Observable notebook 上使用 svg.js

使用 EncryptedLocalStore 时出现 Javascript 错误

javascript - 通过一个编辑按钮在两种表单之间切换

javascript - HTML 中的当前时间 (Javascript)

javascript - JsPDF addImage jpeg 背景为黑色

javascript - 在绘制矩形之前更改 lineCap 和 lineJoin 没有任何作用?

javascript - 添加事件监听器以在 videojs 中的运行时获取视频持续时间

html - css href 和链接

javascript - 如何将 jade-agents (java) 和 babylon.js (html/javascript) - Servlet 连接到 html?

java - KeyListener 仅在单击 Canvas 后才激活