javascript - 大图像 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);
}
解决方案
大图像将导致 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 - 带有输入、按钮和图片的 Javascript 动态表
- javascript - 我收到未定义的 javascript 警报
- linux - 无法对远程服务器进行 SSH。错误:ssh_exchange_identification:读取:对等方重置连接
- ruby-on-rails - “错误”部分适用于“新”用户,但不适用于“编辑”用户
- powershell - HTML 到 CSV 文件的转换
- powershell - 触发远程powershell脚本独立运行
- javascript - CSS 网格。我当前的布局在 chrome 上按预期工作,但在 Firefox 上没有
- c# - uwp 如何读取指定目录下的文件
- jenkins - 执行 TestNG 测试时出错,使用 Gradle 的 WebDriver 的 Cucumver 场景
- bash - 使用 bash 的部署脚本