Я делаю систему кеширования текста для html5 canvas. Мне нужно знать, какой из них дает лучшую производительность. Очистить существующий холст с помощью clearRect или создать холст еще раз?
Редактировать: добавлено несколько кодов.
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 вместо создания холста снова.
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;
}
}