[英]Performance: Html5 Canvas / Javascript - Moving the background image using canvas.drawImage vs canvas.style
我有一个基于position
向上、向下、向左和向右滚动的背景,并且想知道每次position
更改时使用drawImage()
与只绘制一次整个背景并移动 canvas 是否有任何显着的性能差异canvas.style
使用 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
使用 canvas.style
canvas.width = widthofbackgroundImg;
canvas.height = heightofbackgroundImg;
//draw entire background only once
canvas.drawImage(backgroundImg, 0, 0, widthofbackgroundImg, heightofbackgroundImg);
..然后
//move the entire canvas on every position change
canvas.style.left = positionX;
canvas.style.up = positionY;
这是两种不同的方法,具体取决于浏览器处理(不同的浏览器可能会在渲染中设置不同的优先级)。 当然,将 canvas 图像移动drawImage
是没有意义的,如果没有其他变化并且只有初始绘制。 不要使用canvas.style.left
和canvas.style.right
我建议您使用transform = translate3d(x, y, 0)
并使用您的开发工具测试性能改进。 这将通过 GPU 呈现并且可能会提高速度。 它将防止通常耗时的回流。 此外,交替读取和写入 DOM 可能会降低性能。 这将有助于首先进行所有读取(获取位置,滚动 position 等),将其保存在变量中,然后写入所有内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.