
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.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
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 600pxThese 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
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.