gpt4 book ai didi

javascript - 创建新 Canvas VS clearRect

转载 作者:行者123 更新时间:2023-11-30 13:59:41 24 4
gpt4 key购买 nike

我正在为 html5 canvas 制作一个文本缓存系统。我需要知道哪一个性能更好。使用 clearRect 清除现有 Canvas 还是再次创建 Canvas ?

编辑:添加了一些代码。

function textBuffer(text, font, fill="white", stroke=false, lw=0) {
let buffer = document.createElement("canvas");
let bCtx = buffer.getContext("2d");
ctx.font = font;
let d = ctx.measureText(text);
buffer.width = d.width + lw * 2;
buffer.height = parseInt(font.replace(/[^0-9]/g, "")) + lw;
bCtx.font = font;
bCtx.textBaseline = "top"
if(stroke) {
bCtx.lineWidth = lw;
bCtx.strokeStyle = stroke;
bCtx.strokeText(text, lw / 2, lw / 2);
}
bCtx.fillStyle = fill;
bCtx.fillText(text, lw / 2, lw / 2);
return buffer;
}

这是使用 clearRect 而不是再次创建 Canvas 的其他代码。

class Text {
...
render() {
ctx.font = this.font;
this.canvas.width = ctx.measureText(this.text).width;
this.canvas.height = this.fontSize;
this.ctx.clearRect(this.canvas.width, this.canvas.height);

this.ctx.textBaseline = "top";
this.ctx.textAlign = "center";
this.ctx.font = this.font;
this.ctx.strokeStyle = this.strokeColor;
this.ctx.lineWidth = this.lineWidth;
if(this.strokeColor) {
this.ctx.strokeText(this.text, 0, 0);
}
this.ctx.fillText(this.text, 0, 0);

return this.canvas;
}
}

最佳答案

如果您多次使用此方法,那么一定要使用第二个版本。

生成新的 Canvas 元素及其上下文会浪费内存,因此会迫使垃圾收集器更频繁地启动,这可能会导致整个应用程序变慢。

但是,由于您确实调整了 Canvas 的大小,请注意您不需要 clearRect 调用,它已经很清楚了。

关于javascript - 创建新 Canvas VS clearRect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56543152/

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