Canvas Rendering

Adventures in Immediate Mode Graphics on the Web

Evert Timberg

June 2, 2021

What is the Canvas?

  • Bitmap drawing surface added in HTML5
  • Provides view for immediate mode (2d) and WebGL rendering
  • Uses pixels* as coordinates

CSS Pixels vs Device Pixels

  • CSS Pixels: Famously complicated definition
    The reference pixel is the visual angle of one pixel on a device with a pixel density of 96dpi and a distance from the reader of an arm’s length.
  • Device Pixels: Pixels on the actual screen being used for display
  • Related via devicePixelRatio.
    
    const devicePixelWidth = window.devicePixelRatio * window.innerWidth;
          
  • Canvas uses device pixels
  • Future topic: Handling retina displays

Using the Canvas


<canvas id="our-canvas"></canvas>
  

const canvas = document.getElementById('our-canvas');
const ctx = canvas.getContext('2d');
  

Drawing Simple Shapes


const canvas = document.getElementById('our-canvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'rgba(255, 0, 0, 0.5)';
ctx.fillRect(50, 100, 200, 100);
  

Drawing Paths


const ctx = document.getElementById('our-canvas').getContext('2d');
ctx.fillStyle = 'rgba(255, 0, 0, 0.5)';
ctx.strokeStyle = 'rgba(0, 255, 0, 0.5)';
ctx.lineWidth = 5;

ctx.beginPath(); ctx.moveTo(100, 100); ctx.lineTo(200, 100); // Horizontal Line ctx.arcTo(250, 150, 200, 200, 50); ctx.closePath();

ctx.fill(); ctx.stroke();

State Management

Problem: Since the Canvas context has state, how do we manage that?

Answer: The context state can be saved to a stack and restored


ctx.fillStyle = 'blue';
ctx.save();
ctx.fillStyle = 'red';
ctx.fillRect(0, 0, 50, 50); // red
ctx.restore();
ctx.fillRect(100, 0, 50, 50); // blue
  

Text Rendering


// Vertical alignment of the text with respect to the draw point
ctx.textBaseline = 'top';
// Horizontal alignment of the text with respect to the draw point
ctx.textAlign = 'start';
ctx.fillText("Text String", 50, 100);
  

Resources