
HTML Canvas Basics & DPR Drawing Techniques
Canvas is an HTML5 element that lets you draw graphics on web pages using JavaScript. Think of it as a "drawing board" where you can create visuals with JS.
Using Canvas is simple. Just add a <canvas>
tag in HTML, then get its drawing context in JS.
<canvas id="myCanvas" width="500" height="300"></canvas>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// Draw a red rectangle
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 100, 100);
The fillRect
method helps you draw rectangles easily.
You can also draw images on Canvas:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
const img = new Image();
img.src = 'path/to/image.jpg';
img.onload = function() {
// Draw image at original size
ctx.drawImage(img, 0, 0);
// Draw scaled image (200px width)
ctx.drawImage(img, 0, 0, 200, img.height * (200/img.width));
};
Sometimes images may appear blurry. This happens when Canvas size is too small for the screen resolution. Let's fix this.
These properties control Canvas's actual pixel size for drawing.
canvas.width = 800; // Set width to 800px
canvas.height = 600; // Set height to 600px
These show Canvas's display size on the webpage (set by CSS).
#myCanvas {
width: 400px;
height: 300px;
}
Feature | width /height | clientWidth /clientHeight |
---|---|---|
Type | Read/write | Read-only |
Unit | Pixels | Pixels |
Effect | Drawing area | Display size |
Default | 300x150px | CSS determines |
Note: When canvas.width < CSS width × DPR
, browsers stretch pixels, causing blurriness.
DPR (Device Pixel Ratio) means how many physical pixels make one CSS pixel. High-DPR screens (like Retina) use more pixels per CSS pixel.
const dpr = window.devicePixelRatio || 1;
Without adjustment, Canvas drawings may look blurry on high-DPR screens.
Adjust Canvas size to match DPR:
function setupCanvas(canvas) {
const dpr = window.devicePixelRatio || 1;
const rect = canvas.getBoundingClientRect();
// Set actual drawing size
canvas.width = rect.width * dpr;
canvas.height = rect.height * dpr;
// Set display size
canvas.style.width = rect.width + 'px';
canvas.style.height = rect.height + 'px';
// Scale the drawing context
const ctx = canvas.getContext('2d');
ctx.scale(dpr, dpr);
return ctx;
}
// Example
const canvas = document.getElementById('myCanvas');
const ctx = setupCanvas(canvas);
// Now drawings will be sharp
ctx.fillRect(10, 10, 100, 100);
For best results:
- When
canvas.width === CSS width × DPR
: 1 Canvas pixel = 1 physical pixel (sharpest) - When
canvas.width < CSS width × DPR
: Canvas pixels stretch (blurry) - When
canvas.width > CSS width × DPR
: Canvas pixels compress (sharp but may waste resources)
This ensures clear graphics on all screens.