wmash wmash - 1 year ago 61
Javascript Question

Set canvas shapes size as percentage of canvas

I've seen a couple of questions on here that are asking how to set the size of the canvas relative to the window it's in:

  1. Resize HTML5 canvas to fit window

  2. Relatively sizing HTML Canvas

What I wanna know is if I can set shapes (i.e.
) inside the canvas relative to the size. For example:

canvas.style.width = 100;
canvas.style.height = 30;

canvasContext.fillRect(0, 0, "100%", "80%");

I have tried setting the
in pixels with the same size as the canvas thinking it would still be relative to the window but didn't turn out that way.
Instead, if I set
canvasContext.fillRect(0, 0, 100, 30);
, it would be relative to the canvas.


Realised my error and stupidity here. When trying to set the
of the rectangle to the canvas width, I was using
and not 'canvas.width`. I seemed to have forgotten basic HTML for a second...

Answer Source

What prevents you from simply accessing the canvas width on draw?

var canvas = document.getElementById("canvas");
var canvasContext = canvas.getContext("2d");
canvas.width = 100;
canvas.height = 30;

function draw(color) {
  canvasContext.clearRect(0, 0, canvas.width, canvas.heigh);
  canvasContext.fillStyle = color;
  canvasContext.fillRect(0, 0, canvas.width, canvas.height * 0.5);

setTimeout(function() {
  canvas.height *= 2;
}, 1000);

setTimeout(function() {
  canvas.height *= 2;
}, 2000);
<canvas id="canvas" style="border: 1px solid black"></canvas>