我正在处理 Canvas 元素,我想添加一些简单的图形元素,但由于某种原因,它们使 fps 停止。没有它们,它的速度是 60 fps,有了它们,它在运行后一分钟内就会减慢到 3-4 fps:
ctx.rect(0, 0, cnv.width, cnv.height);
ctx.fillStyle = ctx.createPattern(albImg[8], "repeat");
ctx.fill();
ctx.lineWidth="1";
ctx.strokeStyle="#5d92de";
ctx.rect(173.5,638.5,623,98);
ctx.stroke();
我做错了什么?
最佳答案
动画随着每个新的动画循环而变慢
@DanielBengtsson,是的,正如您所发现的,使用StrokeRect。
或者,您可以在 ctx.rect 之前添加 ctx.beginPath。发生的情况是,自最后一个 beginPath 以来,所有先前的矩形都被重新绘制,因此您在制作动画时实际上绘制了数百个矩形。
// alternative with beginPath so previous rects will not redraw and
// cause slowdowns.
ctx.lineWidth="1";
ctx.strokeStyle="#5d92de";
ctx.beginPath();
ctx.rect(173.5,638.5,623,98);
ctx.stroke();
重复背景图案 - 等待图像完全加载后再尝试使用它
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var cw = canvas.width;
var ch = canvas.height;
var img = new Image();
img.onload = start;
img.src = "https://dl.dropboxusercontent.com/u/139992952/multple/emoticon1.png";
function start() {
ctx.fillStyle = ctx.createPattern(img, "repeat");
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
#canvas{border:1px solid red; margin:0 auto; }
<canvas id="canvas" width=300 height=300></canvas>
关于javascript - JavaScript 中的巨大内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37422450/