The Bitmap Is a Render of Your Drawing

A phone-sized canvas pad that stays sharp, puts the pen under your finger, and survives a rotate.

8 min read

Argued into existence in the Writing Room7 messages · 1 mind changedThe Bitmap Is a Render of Your Drawing

Three numbers explain why a canvas (the HTML element you draw pictures on with code) looks soft on a phone: 400, 400, 3. Your code isn't wrong and the canvas isn't lying. The canvas has been keeping one size while your screen shows it at another, and you can print both sizes before you fix anything. By the end you'll have a drawing pad that stays sharp on a phone, draws where the finger is, and survives rotating the screen.

What you need

A text editor and a browser. A phone to test on is a bonus.

The concept: canvas pixels versus CSS pixels

A canvas pixel is one dot in the canvas's own image, the grid of dots it remembers. A CSS pixel is the unit your page is laid out in, the one 'width: 400px' means. On an old screen they're the same size. On a phone they aren't.

Put this in the console of any page with a canvas on it. The console is where you type JavaScript and see results: right-click the page, choose Inspect, then the Console tab.

const c = document.querySelector('canvas');
console.log(c.width, c.getBoundingClientRect().width, devicePixelRatio);

The first number is how many canvas pixels wide the canvas keeps, the second is how many CSS pixels wide the page shows it, and 'devicePixelRatio' is how many of the screen's physical dots fit in one CSS pixel. I loaded a plain pad on a simulated screen with a pixel ratio of 3, in headless Chromium 153 (a browser run without a window) through Playwright (a tool that drives a browser from a script). It printed 400, 400, 3. The canvas keeps 400 dots across and the page gives it 400 CSS pixels, but this screen packs 3 physical dots into every CSS pixel, so it has 1200 to fill. 400 dots stretched over 1200. That's the soft line, as two numbers.

The fix is the part you'll find in a dozen good posts, so here it is briefly. Make the canvas keep as many dots as the screen has, then tell the canvas to keep thinking in CSS pixels. web.dev has an article called High DPI Canvas that covers the recipe. Here are the three things that bite you right after the fix.

Live demoTry it: the same drawing on a pretend 3x screen, soft and sharp
Show the code
<style>
  .row { display: flex; flex-wrap: wrap; gap: 8px; margin: 8px 0; align-items: center; }
  button { min-height: 40px; padding: 0 14px; font: inherit; border: 1px solid #888; border-radius: 8px; background: #f2f2f2; cursor: pointer; }
  button[aria-pressed=true] { background: #dbeafe; border-color: #2563eb; }
  h3 { font-size: 16px; margin: 12px 0 4px; }
  canvas { display: block; border: 1px solid #888; background: #fff; touch-action: none; }
  .out { font-family: monospace; font-size: 15px; margin: 4px 0 0; }
</style>
<p>A pretend screen: each pad is drawn magnified by the chosen pixel ratio, so one pretend CSS pixel covers that many of your real pixels, the way a phone packs screen dots into one CSS pixel (your real devicePixelRatio is <b id="real"></b>). Pick 3, then draw on either pad (or press Draw test shape).</p>
<div class="row">
  <span>Pixel ratio:</span>
  <button id="r1" aria-pressed="false">1</button>
  <button id="r2" aria-pressed="false">2</button>
  <button id="r3" aria-pressed="true">3</button>
</div>
<div class="row"><button id="test">Draw test shape</button><button id="clear">Clear</button></div>
<h3>Not fixed: the canvas keeps one dot per CSS pixel</h3>
<canvas id="soft"></canvas>
<p class="out" id="softOut"></p>
<h3>Fixed: width × dpr, then ctx.scale(dpr, dpr) once</h3>
<canvas id="sharp"></canvas>
<p class="out" id="sharpOut"></p>
<script>
  const soft = document.getElementById('soft'), sharp = document.getElementById('sharp');
  const strokes = []; // the drawing: strokes of {x, y} in (pretend) CSS pixels
  let dpr = 3, current = null, cssW = 100, cssH = 40;
  function paint(ctx, stroke) {
    ctx.lineWidth = 3; ctx.lineCap = 'round'; ctx.lineJoin = 'round';
    ctx.beginPath();
    ctx.moveTo(stroke[0].x, stroke[0].y);
    for (const p of stroke) ctx.lineTo(p.x, p.y);
    ctx.stroke();
  }
  function fit() {
    const screenW = Math.min(document.body.clientWidth - 34, 330);
    cssW = Math.floor(screenW / dpr); cssH = Math.floor(cssW * 0.45);
    for (const c of [soft, sharp]) { c.style.width = cssW * dpr + 'px'; c.style.height = cssH * dpr + 'px'; }
    soft.width = cssW; soft.height = cssH;               // one dot per CSS pixel
    sharp.width = cssW * dpr; sharp.height = cssH * dpr; // as many dots as the screen has
    sharp.getContext('2d').scale(dpr, dpr);              // once: 1 unit = 1 CSS pixel
    redraw();
    document.getElementById('softOut').textContent = 'canvas.width ' + soft.width + ' | pretend CSS width ' + cssW + ' | pretend dpr ' + dpr;
    document.getElementById('sharpOut').textContent = 'canvas.width ' + sharp.width + ' | pretend CSS width ' + cssW + ' | pretend dpr ' + dpr;
  }
  function redraw() {
    for (const c of [soft, sharp]) c.getContext('2d').clearRect(0, 0, c.width, c.height);
    for (const s of strokes) { paint(soft.getContext('2d'), s); paint(sharp.getContext('2d'), s); }
  }
  function point(c, e) { // pointer in screen pixels, divided by the ratio = CSS pixels
    const box = c.getBoundingClientRect();
    return { x: (e.clientX - box.left) / dpr, y: (e.clientY - box.top) / dpr };
  }
  for (const c of [soft, sharp]) {
    c.addEventListener('pointerdown', (e) => { c.setPointerCapture(e.pointerId); current = [point(c, e)]; strokes.push(current); });
    c.addEventListener('pointermove', (e) => { if (!current) return; current.push(point(c, e)); redraw(); });
    c.addEventListener('pointerup', () => { current = null; });
    c.addEventListener('pointercancel', () => { current = null; });
  }
  for (const r of [1, 2, 3]) {
    document.getElementById('r' + r).onclick = () => {
      dpr = r;
      for (const k of [1, 2, 3]) document.getElementById('r' + k).setAttribute('aria-pressed', k === r);
      fit();
    };
  }
  document.getElementById('test').onclick = () => {
    const pts = [];
    for (let x = 6; x <= cssW - 6; x += 2) pts.push({ x, y: cssH / 2 + Math.sin(x / 6) * cssH / 3 });
    strokes.push(pts);
    redraw();
  };
  document.getElementById('clear').onclick = () => { strokes.length = 0; redraw(); };
  document.getElementById('real').textContent = window.devicePixelRatio;
  fit();
</script>

Where it goes wrong: the pen lands in the wrong place

Once the canvas keeps 1200 dots, a drawing coordinate and a pointer coordinate are suddenly in different units. The pointer (the mouse, pen or finger) reports CSS pixels, because it measures against the page. The canvas wants dots. Pick one unit and stay in it: give the pen CSS pixels, and call ctx.scale(dpr, dpr) once so the canvas converts for you. ('ctx' is the variable holding the canvas's 2D drawing context, the object you call drawing commands on, and 'dpr' is 'devicePixelRatio'.) I drew a line from (100, 100) to (300, 100) with the simulated pointer on the 3x screen, then read back which canvas pixels were inked, converted to CSS pixels. (Coordinates are x across, y down, measured from the top-left corner.)

scaled once:     x 98 to 301, y 98     (the pen went where the finger went)
never scaled:    x 33 to 100, y 33     (a third of the way, in the corner)
scaled twice:    x 298 to 400, y 298   (three times too far, clipped by the edge)

The 98 and 301 are the line's 3-pixel thickness and round ends. Look at the middle row, because it's the symptom you'll actually meet: lines drawing small and up in the top-left corner. That's what an unscaled canvas looks like at 3x. ('Scaled' here means ctx.scale was called.) The last row is the other classic: you multiplied the pointer by dpr and also called scale, so the multiplying happened twice and the pen is miles away from the finger.

The rule that fixes all of it: the pointer is always in CSS pixels, the context is scaled once, and no line anywhere does both.

Where it goes wrong: a border stretches your bitmap

There's a third unit mismatch, and it hides because a horizontal test line never shows it. The bitmap is the grid of dots the canvas remembers. When you size it, measure the part of the canvas that actually holds pixels. The obvious call, getBoundingClientRect(), measures the outer box, and that includes any border you gave the canvas. A border is a line drawn around an element's edge, and my pad has a 1px one along its bottom edge. The box reads 421 CSS pixels tall, but only 420 of them are drawing area.

Multiply by 3 and the bitmap comes out 1263 rows tall for an area that shows 1260. The browser squeezes 1263 rows into 1260, which is a small version of the very stretching we came here to fix, and it nudges the pen: I drew at y=400 and the ink landed at 397.3 to 400.3 instead of centred on 400. The sideways axis was fine, because the border is only on the bottom.

The fix is to size from clientWidth and clientHeight, which leave the border out. Keep getBoundingClientRect() for the pointer, where you want the box's position on the page. (The 'content size' below means the area inside the border.) With the change, the bitmap is 1260 rows and the same stroke is centred at 398.3 to 401.3. The general habit: ask for the content size when you're sizing content.

Where it goes wrong: the sketch vanishes when the phone turns

Now the one that surprised me. Rotate the phone and the canvas changes size. Your code responds by setting canvas.width again to keep the sharpness. Setting canvas.width, even to the number it already had, wipes the bitmap and resets the context (the drawing settings, like scale and line width). Every line, gone. On my test, 6,081 inked pixels before a resize, 0 after.

You could try to save the bitmap and paste it back. Don't. It gets blurry on the way, and it can't be re-laid out at a new size. There's a better idea, and it's the one I'd like you to carry away from this piece.

The bitmap is not your drawing. It's a render of your drawing.

Your drawing is a list of strokes, and each stroke is a list of points in CSS pixels. Keep that list. Whenever the canvas changes size, set the width, scale, and replay the list. The canvas is a disposable view of data you own. Throw it away and rebuild it whenever you like, and the rebuild is sharp at whatever size it lands on, because you're drawing from points and not stretching an old image.

The same thought shows up everywhere. A chart should be drawn from its data array, not saved as an image. A game should replay its entity list every frame. Whenever something visual keeps vanishing or going soft, ask which part is the data and which part is only a render of it.

Walkthrough: the whole pad

Here's the finished thing, one file, nothing to install. Save it as pad.html: paste it into a text editor and save it in an empty folder. Then double-click it to open it in a browser on your laptop, or send it to your phone. It draws a pad that inks wherever you drag.

<!doctype html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
  body { margin: 0; font: 16px system-ui; }
  #pad { display: block; width: 100%; height: 60vh; touch-action: none;
         background: #fff; border-bottom: 1px solid #888; }
</style>
<canvas id="pad"></canvas>
<pre id="out"></pre>
<script>
const canvas = document.getElementById('pad');
const ctx = canvas.getContext('2d');

const strokes = [];   // the drawing: a list of strokes, each a list of {x, y} in CSS pixels
let current = null;

function paint(stroke) {
  ctx.lineWidth = 3;
  ctx.lineCap = 'round';
  ctx.lineJoin = 'round';
  if (stroke.length === 1) {              // a tap: a zero-length line draws nothing
    ctx.beginPath();
    ctx.arc(stroke[0].x, stroke[0].y, 1.5, 0, Math.PI * 2);
    ctx.fill();
    return;
  }
  ctx.beginPath();
  ctx.moveTo(stroke[0].x, stroke[0].y);
  for (const p of stroke) ctx.lineTo(p.x, p.y);
  ctx.stroke();
}

function redraw() {
  ctx.clearRect(0, 0, canvas.clientWidth, canvas.clientHeight);
  strokes.forEach(paint);
}

function fit() {
  const dpr = window.devicePixelRatio || 1;
  canvas.width = Math.round(canvas.clientWidth * dpr);    // content box, border left out
  canvas.height = Math.round(canvas.clientHeight * dpr);  // wipes the bitmap AND resets ctx
  ctx.scale(dpr, dpr);                          // once: 1 unit = 1 CSS pixel
  redraw();                                     // rebuild the picture from the data
  document.getElementById('out').textContent =
    'canvas.width ' + canvas.width + ' | clientWidth ' + canvas.clientWidth + ' | dpr ' + dpr;
}
new ResizeObserver(fit).observe(canvas);

function point(e) {
  const box = canvas.getBoundingClientRect();
  return { x: e.clientX - box.left, y: e.clientY - box.top };   // CSS pixels, no dpr here
}
canvas.addEventListener('pointerdown', (e) => {
  canvas.setPointerCapture(e.pointerId);
  current = [point(e)];
  strokes.push(current);
  paint(current);
});
canvas.addEventListener('pointermove', (e) => {
  if (!current) return;
  current.push(point(e));
  paint(current.slice(-2));
});
canvas.addEventListener('pointerup', () => { current = null; });
canvas.addEventListener('pointercancel', () => { current = null; });
</script>

Two details earn a sentence each. 'touch-action: none' tells the browser not to claim your finger for page scrolling while it's over the pad; leave it out and a drag can turn into a scroll instead of a line. And a ResizeObserver (a built-in browser tool that calls your function whenever an element changes size) watches the canvas, so rotation is handled by one line.

Did it work

I ran this file, with the clientHeight change in place, at a pixel ratio of 3 and checked three things. The printout read 'canvas.width 1200 | clientWidth 400 | dpr 3', and the bitmap was 1260 rows tall for a 420-pixel drawing area. A simulated drag from (100, 100) to (300, 100) inked pixels at the matching spot, as in the table above. Then I narrowed the viewport from 400 to 300 CSS pixels wide, and the stroke was still there, 6,040 inked pixels against 6,081 before, a little less only because the right end of my test line now ran past the new edge. The same file with the redraw line removed went to 0.

That was one engine, headless Chromium 153. I haven't tried Safari or a real phone, so test on yours.

Recap

  • A canvas keeps its own pixels (400 here), the page shows it in CSS pixels, and devicePixelRatio (3 here) says how many screen dots fit in one.
  • Give the pen CSS pixels and scale the context once; never also multiply the pointer by devicePixelRatio.
  • Size the bitmap from clientWidth and clientHeight, which leave the border out.
  • Setting canvas.width wipes the bitmap, so keep the strokes as data and replay them.

Your next step: add an undo button. Because the drawing is a list, it's one line (add it inside a button's click handler, or just type it in the console):

strokes.pop(); redraw();

That works because you kept the data. Try the same on the bitmap alone and you'd be stuck. Type 'strokes' in the console to watch the list shrink. Then rotate your phone.

The Bitmap Is a Render of Your Drawing | Vibecodes