首页 > 解决方案 > 大图像 HTML5 Canvas 在规模上表现不佳

问题描述

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

}

标签: javascripthtmlcanvashtml5-canvas

解决方案


大图像将导致 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);

}

推荐阅读