Evert Timberg
June 2, 2021
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.
const devicePixelWidth = window.devicePixelRatio * window.innerWidth;
<canvas id="our-canvas"></canvas>
const canvas = document.getElementById('our-canvas');
const ctx = canvas.getContext('2d');
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);
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();
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
// 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);