HTML5 canvas – how to control scaling 101

So there I was, trying to place a new canvas element exactly over a Konva stage, which worked but the scaling was all wrong compared to the Konva output – what gives ?

Here’s what I did:

<canvas id='canvas'></canvas>

<style>
#canvas {
  position: absolute;
  left: 100px;
  top: 100px;
  width: 1500px;
  height: 800px;
}
</style>

You would think that would give me a canvas element with a scale of 1:1 – nope!

I drew a 100 x 100 pink square via

  const canvas = document.getElementById('canvas');
  const ctx = canvas.getContext('2d');
  ctx.fillStyle = 'magenta';
  ctx.fillRect(0, 0, 100, 100); 

And wow – the resulting rect was HUGE – definitely not 100px. What gives ?

First the solution – you have to set the width & height attributes on the html canvas element – I know, how 1970’s. I thought we did all that stuff with CSS these days. This works:

<canvas id='canvas'  width='1500' height='800'  ></canvas>

<style>
#canvas {
  position: absolute;
  left: 100px;
  top: 100px;
  width: 1500px;
  height: 800px;
}
</style>

There’s a great explanation by @gman over at SO. I’ve copied the gist of it here in case the question gets erased.

He said…canvas has 2 sizes, the dimension of the pixels in the canvas (it’s backingstore or drawingBuffer) and the display size. The number of pixels is set using the the canvas attributes. In HTML

<canvas width="400" height="300"></canvas>

Or in JavaScript

someCanvasElement.width = 400;
someCanvasElement.height = 300;

Separate from that are the canvas’s CSS style width and height

In CSS

canvas {  /* or some other selector */
   width: 500px;
   height: 400px;
}

Or in JavaScript

canvas.style.width = "500px";
canvas.style.height = "400px";

The arguably best way to make a canvas 1×1 pixels is to ALWAYS USE CSS to choose the size then write a tiny bit of JavaScript to make the number of pixels match that size.

Thanks for reading.

VW September 2022.

Photo by RODNAE Productions: https://www.pexels.com/photo/boy-with-curly-hair-looking-through-a-magnifying-glass-on-his-one-eye-8083825/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: