Canvas drawImage 在大型源上运行缓慢
Canvas drawImage is slow on large source
我正在制作一款游戏,并且正在创建一个摄像机来跟随玩家。我有一个 4096x4096 像素的大 canvas(游戏地图)。为此,我只想绘制其中的一部分:
ctx.drawImage( canvas, 0, 0, 800, 600, 0, 0, 4096, 4096 );
在每一帧之前我会调用:
ctx.clearRect( 0, 0, 800, 600 );
只清空摄像头。我可以看到 drawImage 非常慢,性能方面。我的游戏地图是否很大,并且不是由 drawImage 处理的?如何创建平滑的渲染?
我们需要查看更多代码才能真正了解性能问题出在哪里。
很可能是尺寸让您放慢了速度。 drawImage()
是用于更新 canvas 的 easily the fastest method,但还有其他一些事情会大大降低您的速度,例如使用 getImageData()
或效率低下的 Javascript。
我认为您可能误解了 drawImage
的一些论点。
如您所写 drawImage
,它将从源文件中剪裁 800x600。然后它会将其放大到 4096x4096。它最终会在 canvas.
上绘制 4096x4096
所以你有一个 4096x4096 spritesheet。您想要从该 spritesheet 中剪裁一个 800x600 的部分并将剪裁绘制到 canvas:
// this will clip 800x600px from your source image
// starting at top-left == [1600,0]
// and it will paint that clipping at [0,0] on the canvas
// while not changing the clipping size from its original 800x600
ctx.drawImage(
yourImage // use yourImage as the source image
1600,0 // clip from the source image with top-left at [1600,0]
800,600 // clip 800x600px from the source
0,0 // paint the clipping at [0,0] on the canvas
800,600 // use the same 800x600 size that was clipped
);
我正在制作一款游戏,并且正在创建一个摄像机来跟随玩家。我有一个 4096x4096 像素的大 canvas(游戏地图)。为此,我只想绘制其中的一部分:
ctx.drawImage( canvas, 0, 0, 800, 600, 0, 0, 4096, 4096 );
在每一帧之前我会调用:
ctx.clearRect( 0, 0, 800, 600 );
只清空摄像头。我可以看到 drawImage 非常慢,性能方面。我的游戏地图是否很大,并且不是由 drawImage 处理的?如何创建平滑的渲染?
我们需要查看更多代码才能真正了解性能问题出在哪里。
很可能是尺寸让您放慢了速度。 drawImage()
是用于更新 canvas 的 easily the fastest method,但还有其他一些事情会大大降低您的速度,例如使用 getImageData()
或效率低下的 Javascript。
我认为您可能误解了 drawImage
的一些论点。
如您所写 drawImage
,它将从源文件中剪裁 800x600。然后它会将其放大到 4096x4096。它最终会在 canvas.
所以你有一个 4096x4096 spritesheet。您想要从该 spritesheet 中剪裁一个 800x600 的部分并将剪裁绘制到 canvas:
// this will clip 800x600px from your source image
// starting at top-left == [1600,0]
// and it will paint that clipping at [0,0] on the canvas
// while not changing the clipping size from its original 800x600
ctx.drawImage(
yourImage // use yourImage as the source image
1600,0 // clip from the source image with top-left at [1600,0]
800,600 // clip 800x600px from the source
0,0 // paint the clipping at [0,0] on the canvas
800,600 // use the same 800x600 size that was clipped
);