gpt4 book ai didi

javascript - 为什么这个 Canvas 绘图会导致内存泄漏?

转载 作者:行者123 更新时间:2023-11-28 14:28:12 25 4
gpt4 key购买 nike

以下代码导致内存/CPU 泄漏 - CPU 使用率迅速增加并在几分钟内达到 100%,这对性能不利。我想了解为什么会发生这种情况,这样我以后就不会犯类似的错误。

function drawBoard(w, h, p, context) {

for (var x = 0; x <= w; x += 40) {
context.moveTo(0.5 + x + p, p);
context.lineTo(0.5 + x + p, h + p);
}


for (var x = 0; x <= h; x += 40) {
context.moveTo(p, 0.5 + x + p);
context.lineTo(w + p, 0.5 + x + p);
}

context.strokeStyle = "black";
context.stroke();

}
let cancel
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
let context = ctx
function Loop() {
cancel = window.requestAnimationFrame(Loop)
drawBoard(800, 600, 10, context)
}
Loop()

最佳答案

这是因为你从未使用过 context.beginPath();

这来自 MDN:“Canvas 2D API 的 CanvasRenderingContext2D.beginPath() 方法通过清空子路径列表来启动新路径”

function drawBoard(w, h, p, context) {

for (var x = 0; x <= w; x += 40) {
context.beginPath();
context.moveTo(0.5 + x + p, p);
context.lineTo(0.5 + x + p, h + p);
context.stroke();

}


for (var y = 0; y <= h; y += 40) {
context.beginPath();
context.moveTo(p, 0.5 + y + p);
context.lineTo(w + p, 0.5 + y + p);
context.stroke();
}

}
let cancel
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
let w = canvas.width = 800;
let h = canvas.height= 600;
let context = ctx
function Loop() {
cancel = window.requestAnimationFrame(Loop);
context.clearRect(0,0,w,h)
drawBoard(w, h, 10, context)
}
Loop()
<canvas id="canvas"></canvas>

关于javascript - 为什么这个 Canvas 绘图会导致内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52488111/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com