Centering and zooming the canvas

P5 sketches run inside an html element called canvas which is created with create canvas. Centering within a page requires some css magic.

In the index.html style tag, replace the existing canvas item with

    canvas {
      vertical-align: middle;
      margin: auto;

      /* remove these if you DON'T want sharp pixel edges*/
      image-rendering: -moz-crisp-edges;
      image-rendering: -webkit-crisp-edges;
      image-rendering: pixelated;

      padding: 0;
      display: block;
      position: absolute;
      margin:auto;
      left: 0;
      right: 0;
      /* remove these two if you don't want vertical alignment */
      top:0;
      bottom: 0;

    }

The canvas can also be accessed and manipulated within the sketch.
This is how you can scale it by multiples of the native size.
Don’t forget to add the image-rendering settings below to the css if you want non antialiased (crisp) pixel for a pixelart project.

 function setup() {
      var canvas = createCanvas(64, 64);
      var pixelScale = 4;

      noSmooth();
      canvas.style("width", width*pixelScale+"px");
      canvas.style("height", height*pixelScale+"px");

    }
Posted in