Farry
Farry

Reputation: 13

creating a new canvas VS clearRect

I am making a text caching system for html5 canvas. I need to know which one gives better performance. Clearing the existing canvas using clearRect or creating the canvas once again?

Edit: Added some codes.

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;
}

Here's the other code which uses clearRect instead of creating the canvas once again.

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;
    }
}

Upvotes: 1

Views: 110

Answers (1)

Kaiido
Kaiido

Reputation: 136796

If you are using this method several times, then use the second version, definitely.

Generating a new canvas element and its context will waste memory, and thus will force the Garbage Collector to kick in more often, which may cause your whole app to slow down.

However, since you do resize your canvas, note that you don't need the clearRect call, its already clear.

Upvotes: 2

Related Questions