我正在尝试使用画布上下文缩放我的(大尺寸: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);

}

关于javascript - 大图HTML5 Canvas在规模上性能较差,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58398080/

10-11 09:15