我正在尝试编写简单的2D俯视格子地图游戏,但在对特定画布区域中的像素进行操作时遇到了问题。我有以下函数:
changeCellBackground(x, y, r, g, b){
let cell = this.context.getImageData(x * this.TILE_SIZE, y * this.TILE_SIZE, this.TILE_SIZE, this.TILE_SIZE);
for(let i=0; i<cell.data.length; i+=4){
cell.data[i] += r;
cell.data[i+1] += g;
cell.data[i+2] += b;
}
this.context.putImageData(cell, x * this.TILE_SIZE, y * this.TILE_SIZE);
}
其中 context 是 canvas 2d 上下文:
this.screen = $('#game');
this.context = this.screen[0].getContext('2d');
一个带有指向图块集的链接的Img标签:
let tileSet = $('<img></img>').attr('src', '../assets/tiles.png');
然而,当我尝试使用上述函数时,我遇到了SecurityError: The operation is insecure.
的错误。据我了解,这是由于CORS限制造成的,所以我尝试在Img
中添加crossOrigin="anonymous"
属性:
let tileSet = $('<img></img>').attr('crossOrigin', 'anonymous').attr('src', '../assets/tiles.png');
但是现在我收到了NS_ERROR_NOT_AVAILABLE:
的错误信息。我猜测这是因为当脚本开始执行时,图片还没有加载完成。我该如何解决这个问题?我尝试了以下方法:
let tileSet = $('<img></img>');
tileSet.onload = function(){
tileSet.attr('crossOrigin', 'anonymous').attr('src', '../assets/tiles.png');
gameScreen.drawAnimatedImage(0, 0, 'waterfall');
gameScreen.drawAnimatedImage(2, 2, 'fountain');
gameScreen.drawAnimatedImage(11, 5, 'street_lamp');
gameScreen.drawAnimatedImage(10, 5, 'street_lamp');
gameScreen.changeCellBackground(10, 15, -30, -30, -30);
};
但它也不起作用——当我在onload
函数末尾设置console.log(tileSet)
时,控制台上没有输出任何内容。看起来onload
函数没有被触发。为什么会出现这种情况,我该如何修复它?
src
属性在你的加载事件处理程序中,但这需要src
被设置以便于某一天触发...将这行代码移到这个处理程序之外。我的看法是这个问题应该作为打字错误而关闭... - Kaiido