我在画布上出现问题,我有一组图像信息,我循环并从中创建图像对象。在每个图像 onload 事件上,我将其绘制到画布上,但这仅在刷新后才有效(一旦图像在缓存中似乎)。
这是我的代码片段
var image = new Image();
image.src = img.src; //got from elsewhere, need to draw a background image first
image.onload = function () {
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
img.parentNode.replaceChild(canvas, img);
var context = canvas.getContext('2d');
context.drawImage(image, 0, 0, canvas.width, canvas.height);
context.globalCompositeOperation = 'source-over';
//looping through my image info
for (var index in anaglyphs){
var anaglyph = anaglyphs[index];
if (anaglyph === undefined) continue;
//If x, y, height and width values are set in Image then set in mask
//otherwise use defaults
var x = 0;
if (anaglyph.x !== undefined) x = anaglyph.x;
var y = 0;
if (anaglyph.y !== undefined) y = anaglyph.y;
var width = canvas.width;
if (anaglyph.width !== undefined) width = anaglyph.width;
var height = canvas.height;
if (anaglyph.height !== undefined) height = anaglyph.height;
var alpha = new Image();
//Use of an intimidate function to stop javascripts closure
//overriding the variables before the onload event fired. Creating
//temporary variables in the intimidate function, which executes
//immediately, and storing the desired values inside them for callback.
(function (){
var xPos = x;
var yPos = y;
var maskWidth = width;
var maskHeight = height;
alpha.onload = function () {
context.drawImage(this, xPos, yPos, maskHeight, maskWidth);
};
})();
alpha.src = "data:"+anaglyph.content+";base64,"+encode64(anaglyph.data);
}
};
刷新后它工作正常,如果我再次使用该脚本打开网页,它将继续正常工作,但是如果我清除缓存并重新打开页面,它将再次失败。它只需要在最新版本的 Firefox 中工作。
谢谢