大图像 HTML5 画布在规模上性能不佳



我正在尝试使用画布上下文缩放我的(大:16200x8100(图像;ctx.scale(),但是当我开始制作动画时,我似乎发现帧之间的延迟非常大,画布适当缩放以垂直适合整个图像,但是如果我根本不从画布缩放开始,我就不会发现这个问题。这有什么原因或解决方案吗?还是图像的绝对尺寸?

image.onload = () => {
//the multiplier by which to scale the canvas context to fit image in canvas vertically
minScale = (canvas.height/image.height);
ctx.scale(minScale, minScale);
leftMostOffset = {x: -image.width, y: 0};
animate();
}

function animate(){
requestAnimationFrame(animate);
ctx.save();
ctx.setTransform(1,0,0,1,0,0);
ctx.clearRect(0,0, ctx.canvas.clientWidth, ctx.canvas.clientHeight);
ctx.restore();
ctx.drawImage(image, rightMostOffset.x, rightMostOffset.y);
ctx.drawImage(image, leftMostOffset.x, leftMostOffset.y);
}

大图像将导致RAM从CPU移动到GPU。这是非常缓慢的。

以画布的分辨率创建图像的副本,并在制作动画时绘制该副本。这在前两帧上会很慢,因为内存仍然需要移动。但是一旦完成,缩放后的图像应该不会变慢

var imageC;
image.onload = () => {
//the multiplier by which to scale the canvas context to fit image in canvas vertically
minScale = (canvas.height/image.height);
leftMostOffset = {x: -image.width, y: 0};
imageC = document.createElement("canvas");
imageC.width = ctx,canvas.width;
imageC.height = ctx.canvas.height;
imageC.ctx = imageC.getContext("2d");
imageC.ctx.scale(minScale, minScale);
// will be slow for first two frames
imageC.ctx.drawImage(image, rightMostOffset.x, rightMostOffset.y);
imageC.ctx.drawImage(image, leftMostOffset.x, leftMostOffset.y);
animate();
}

function animate(){
requestAnimationFrame(animate);
ctx.setTransform(1,0,0,1,0,0);
ctx.clearRect(0,0, ctx.canvas.width, ctx.canvas.height);
ctx.drawImage(imageC,0,0);
}

最新更新