简体   繁体   English

性能:Html5 Canvas / Javascript - 使用 canvas.drawImage 与 canvas.style 移动背景图像

[英]Performance: Html5 Canvas / Javascript - Moving the background image using canvas.drawImage vs canvas.style

I have a background that scrolls up, down, left and right based on position , and was wondering if there is any significant performance difference into using drawImage() every time the position changes vs just drawing the entire background once and moving the canvas around using canvas.style我有一个基于position向上、向下、向左和向右滚动的背景,并且想知道每次position更改时使用drawImage()与只绘制一次整个背景并移动 canvas 是否有任何显着的性能差异canvas.style

Using canvas.drawImage()使用 canvas.drawImage()

//cut piece and draw image to fill canvas every time position changes
canvas.drawImage(backgroundImg, 0 + positionX, 0 + positionY, c.width, c.height, 0, 0, c.width, c.height);

VS VS

Using canvas.style使用 canvas.style

canvas.width  = widthofbackgroundImg;
canvas.height = heightofbackgroundImg;

//draw entire background only once
canvas.drawImage(backgroundImg, 0, 0, widthofbackgroundImg, heightofbackgroundImg);

..then ..然后

//move the entire canvas on every position change
canvas.style.left = positionX;
canvas.style.up   = positionY;

Those are two different approaches which are depending on the browser processing (different browsers might set different priorities in rendering).这是两种不同的方法,具体取决于浏览器处理(不同的浏览器可能会在渲染中设置不同的优先级)。 For sure, it does not make sense to move the canvas image by drawImage , if nothing else changes and there is just an initial draw.当然,将 canvas 图像移动drawImage是没有意义的,如果没有其他变化并且只有初始绘制。 Instead of going with canvas.style.left and canvas.style.right I would suggest you to use transform = translate3d(x, y, 0) and test the performance improvement with your dev tools.不要使用canvas.style.leftcanvas.style.right我建议您使用transform = translate3d(x, y, 0)并使用您的开发工具测试性能改进。 This will be rendered via the GPU and may increase speed.这将通过 GPU 呈现并且可能会提高速度。 It will prevent reflow which is time consuming in general.它将防止通常耗时的回流。 Also the reading from and writing to the DOM in alternation might slow down performance.此外,交替读取和写入 DOM 可能会降低性能。 It will help to first make all reading (get positions, scroll position or the like), save it in variables and then write everything.这将有助于首先进行所有读取(获取位置,滚动 position 等),将其保存在变量中,然后写入所有内容。

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

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