简体   繁体   English

HTML5 Canvas 通过平移与剪辑的平移图像效率

[英]HTML5 Canvas efficiency of panning image by Translate vs. Clipping

There's a bunch of questions on panning a background image in a canvas (ie to simulate a 'camera' in a game with the character in the center) - and most answers suggest using the canvas' translate method.在 canvas 中平移背景图像有很多问题(即在游戏中以角色为中心模拟“相机”) - 大多数答案建议使用画布的translate方法。

But since you have to re-draw the image in each frame anyway, why not just clip it?但是既然你必须在每一帧中重新绘制图像,为什么不直接剪辑呢? Does it matter in terms of efficiency?在效率方面重要吗?

In particular, is panning like this a bad idea?特别是,像这样平移是一个坏主意吗? (This example shows a simplified pan of the camera moving in one direction) (此示例显示了相机在一个方向上移动的简化平移)

let drawing = new Image();
drawing.src = "img_src";
drawing.onload = function () {

    ctx.drawImage(drawing, 0, 0);
    let pos = 0
    
    setInterval(() => {
        pos += 1
        ctx.clearRect(0, 0, cnvs.width, cnvs.height);
        ctx.drawImage(drawing, -pos, 0 ); // "pans" the image to the left using the option `drawImage` parameters `sx` and `sy`
    }, 33);
};

Example result: fiddle示例结果:小提琴

Thanks in advance!提前致谢!

The main advantage of using the transform matrix to control your camera is that you don't have to update all the elements in your world, you just move the world instead.使用变换矩阵来控制相机的主要优点是您不必更新世界中的所有元素,只需移动世界即可。

So yes, if you are willing to move only a single element (be it the background like in your case), moving only that one element might be a better choice.所以是的,如果您只愿意移动一个元素(就像您的情况一样是背景),那么只移动那个元素可能是一个更好的选择。
But if you need several layers of elements to all move relatively to the camera, then using the transformation matrix is a better choice.但是如果您需要几层元素都相对于相机移动,那么使用变换矩阵是更好的选择。

As for the perfs, I didn't ran any benchmarks on this, but I'd suspect it's exactly the same, though beware when messing with the cropping features of drawImage , at least Safari doesn't handle cropping from outside of a source canvas correctly .至于性能,我没有对此进行任何基准测试,但我怀疑它完全相同,尽管在弄乱drawImage的裁剪功能时要小心,至少Safari 不能处理来自源外部的裁剪 canvas正确

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM