DEV Community

Calin Baenen
Calin Baenen

Posted on

Why won't anything draw to my canvas? (fixed)

Original post (which has been edited to be fixed).

Whenever I try to draw a custom image in JS, it doesn't draw anything, when I try to log X or Y in the loop, it returns normal values, when I log the color, it's perfectly normal.

So, why won't it draw anything?

const text = `Example`;



const makeColor = function makeColor(input, maxX=Infinity, maxY=Infinity) {
    let X = 0;
    let Y = 0;

    let peakX = -1;
    let peakY = -1;
    if(maxX < Infinity) maxX;



    const encode = function encode(input) {
        let estr = "";
        for(const chara of input) {
            estr += String(Number(chara.charCodeAt(0), 16));
        }
        return estr;
    };


    const colors = [];
    let color = "";
    let itr = 0;
    for(const chara of encode(input)) {
        color += chara;
        if(color.length >= 6) {
            itr += 1;
            colors.push(color);
            document.writeln(itr+": "+color+"<br/>");
            color = "";
        }
    }

    if(color.length < 6 && color.length > 0) {
        color += "0".repeat(6-color.length);
        colors.push(color);
        document.writeln(color+"<br/>");
        color = "";
    }



    Object.freeze(colors);


    try {
        const canvas = document.getElementById("result");
        const ctx = canvas.getContext("2d");

        try {
            for(const color of colors) {
                console.log(X, Y);
                ctx.fillStyle = "#"+color;
                if(X > maxX) {
                    if(peakX <= -1 || X > peakX) peakX = X-1;
                    X = 0; Y++; ctx.fillRect(X, Y, 1, 1); X++; continue;
                }
                if(Y > maxY) break;
                ctx.fillRect(X, Y, 1, 1); X++;
            }
            if(maxX >= Infinity) peakY = 1;
            canvas.style.width = canvas.width = peakX;
            canvas.style.height = canvas.height = peakY;
        } catch(err) {throw new Error();}
    } catch(err) {console.error("Could not draw image!");}
};



makeColor(text, 30);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)