wmash wmash - 14 days ago 6
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.
rect
) 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
rect
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.

EDIT:

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

Answer

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);
}
draw("#FF0000");

setTimeout(function() {
  canvas.height *= 2;
  draw("#00FF00");
}, 1000);

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