JS -画布从图像文件-工作仅与浏览器缓存存在

JS - Canvas from image file - works only with browser cache present

本文关键字:浏览器 缓存 存在 工作 -画 图像 文件 JS      更新时间:2023-09-26

我的JS代码在画布上绘制图像,使用图像文件。然而,这段代码只能在浏览器缓存存在的情况下工作——当页面第二次加载时。对于空缓存(ctrl +f5),画布是空的。有没有办法在执行代码之前预加载图像文件或其他方式使其第一次工作?

<canvas id="nr"></canvas>
<script>
var ctx = document.getElementById('nr').getContext('2d');
var img = new Image;
img.src = 'tlo.jpg';
var width = img.naturalWidth;
var height = img.naturalHeight;
document.getElementById('nr').width = width;
document.getElementById('nr').height = height;
console.log(width); //prints 0 with cache empty
ctx.drawImage(img, 0,0);
</script>

图像加载是一个异步操作,所以在复制到画布之前等待图像被加载。试试这样写:

var ctx = document.getElementById('nr').getContext('2d');
var img = new Image;
img.src = 'tlo.jpg';
img.onload = function() {
   var width = img.naturalWidth;
   var height = img.naturalHeight;
   document.getElementById('nr').width = width;
   document.getElementById('nr').height = height;
   console.log(width); //prints 0 with cache empty
   ctx.drawImage(img, 0,0);
}

如果您愿意,可以在img元素上注册一个事件侦听器。


我还建议将整个代码块包装在一个函数中,以便在窗口加载事件触发后执行。此时,在您的浏览器中,在页面加载过程中修改DOM元素可能有效,但通常不能保证成功。