'How to convert p5.JS canvas creation code to HTML Canvas

How would I translate this p5.js code into Canvas? The createCanvas method, for example, is not in Canvas. The same goes for draw() and setup().

function setup() {
  createCanvas(300, 300);
}

function draw() {
  background(50);

  for (var r = 0; r < 10; r++) {
    for (var c = 0; c < 10; c++) {
      stroke(0);
      fill(10 * r, 10 * c, 255)
      rect(30, 30, 30, 30);
    }
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.js"></script>


Solution 1:[1]

Converting simple p5 like this is straightforward after checking out a tutorial on basic canvas. That said, p5 is doing a lot under the hood and packing much more functionality into calls like createCanvas, so if you find you're just reinventing many of the abstractions it already provides or using advanced features, it's probably best to just use p5.

rect(30, 30, 30, 30); just keeps drawing on the same spot over and over, so I assume you wanted rect(30 * r, 30 * c, 30, 30);

Also, since you're not animating anything, it's probably best to use p5's noLoop and skip requestAnimationFrame altogether, since it's just burning CPU cycles as it stands here.

const canvas = document.createElement("canvas");
document.body.appendChild(canvas);
canvas.width = canvas.height = 300;
const ctx = canvas.getContext("2d");

(function draw() {
  requestAnimationFrame(draw);
  ctx.fillStyle = "rgb(50, 50, 50)";
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  for (let r = 0; r < 10; r++) {
    for (let c = 0; c < 10; c++) {
      ctx.fillStyle = `rgb(${10 * r}, ${10 * c}, 255)`;
      ctx.fillRect(30 * r, 30 * c, 30, 30);
      ctx.strokeStyle = "#000";
      ctx.strokeRect(30 * r, 30 * c, 30, 30);
    }
  }
})();

Solution 2:[2]

Libraries like p5.js exist because the native API for Canvas is not particularly user friendly. However if you insist on using Canvas directly you should start with something like this tutorial on MDN.

Specifically regarding the methods used in your example (createCanvas, fill, rect), this existing StackOverflow question covers all three.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ggorlen
Solution 2 Paul Wheeler