Why is JS canvas showing up, but not updating?

Viewed 34

I want to create a rectangle canvas that simply shows a few randomy generated particles. I have been messing around with canvas a bit off my project so I understand the basics. However, it seems when I try to integrate a canvas to my project, nothing is working.

The canvas HTML element is properly added to the DOM (I can see it thanks to the dashed border) and it is properly positioned. I can also see the console message "Refreshed" which means the interval works.

BUT the canvas just remains blank, whatever I do. I've tried filling it, drawing circles, strokes and everything, and absolutely NOTHING shows up. It just remains a transparent rectangle.

Below is the (typscript) code that handles the canvas, and the method that calls the canvas:


    // particles canvas
    public static getTooltipParticlesCanvas(rarity: Data.Rarity, id: number) { 
        let posY = 25, posX = 25;
        let canvas = document.createElement("canvas");
        let ctx = canvas.getContext("2d");
        canvas.width = 232;
        canvas.height = 53;
        canvas.style.border = "1px dashed grey";
        canvas.style.position = "absolute";
        canvas.style.left = "0";

        clearInterval(this.particlesTooltipCanvasInterval);
        this.particlesTooltipCanvasInterval = setInterval(() => {
            // erase canvas
            ctx.fillStyle = "white";
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            posY -= 0.25;
    
            ctx.fillStyle = "green";
            ctx.fillRect(posX, posY, 5, 5);
            console.log("Refreshed");
        }, 30);

        return canvas;
    }
    
    public static getWeaponTooltip(weapon: Weapon) {
        let str: string = '';
        // ...
        str += '<div class="canvasWrapper">' + this.getTooltipParticlesCanvas(weapon.rarity).outerHTML + '</div>
        // ...
        return str;
    }

The getWeaponTooltip returns a HTML string that is then appended via .innerHTML on a div.

1 Answers

Your code works fine in isolation (with references to this and the unused rarity and id removed), so the issue is in something you're not showing us.

function getTooltipParticlesCanvas() { 
    let posY = 25, posX = 25;
    let canvas = document.createElement("canvas");
    let ctx = canvas.getContext("2d");
    canvas.width = 232;
    canvas.height = 53;
    canvas.style.border = "1px dashed grey";
    canvas.style.position = "absolute";
    canvas.style.left = "0";
    setInterval(() => {
        // erase canvas
        ctx.fillStyle = "white";
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        posY -= 0.25;

        ctx.fillStyle = "green";
        ctx.fillRect(posX, posY, 5, 5);
    }, 30);

    return canvas;
}

canvas = getTooltipParticlesCanvas();

document.body.appendChild(canvas);

Related