DEV Community

Discussion on: Why won't anything draw on my canvas?

Collapse
 
ducaale profile image
Mohamed Dahir

I take back my comments about document.writeln(). Your problems seem to stem from the following:

  • You are setting the canvas' width and height to peakX and peakY which equal -1;
  • You fillRect calls were drawing boxes that were too tiny. You can make things larger by multiplying them with a scaler value
function makeColor(input, maxX = Infinity, maxY = Infinity) {
  let X = 0;
  let Y = 0;

  let peakX = -1;
  let peakY = -1;

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

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

  for (const color of colors) {
    ctx.fillStyle = "#" + color;
    if (X > maxX) {
      if (peakX <= -1 || X > peakX) peakX = X - 1;
      X = 0;
      Y++;
      console.log(ctx.fillStyle, X, Y, 1, 1)
      ctx.fillRect(X, Y, 1, 1);
      X++;
      continue;
    }
    if (Y > maxY) break;
    ctx.fillRect(X * 25, Y * 25, 25, 25);
    X++;
  }
  if (maxX >= Infinity) peakY = 1;
  //canvas.style.width = canvas.width = peakX;
  //canvas.style.height = canvas.height = peakY;

}

makeColor('Example', 30);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
baenencalin profile image
Calin Baenen

Nevermind. Why is peakX and peakY behaving strangely?

Collapse
 
baenencalin profile image
Calin Baenen

PeakX and PeakY were not negative 1, Peak* changes once Axis is greater than PeakAxis, meaning something went wrong.

Also, I didn't upscale the pixels because I wanted a 1:1 image.