You had some mistakes in your code. First of all, you have rectheight =- 10;
instead of rectheight -= 10
. Your line of code is actually equivalent to rectheight = -10
, so you are just setting both of the variables to -10, not decrementing them by 10.
Then, you used fill
instead of fillRect
. There is a fine difference between them, you may read more here or here. fillRect
is a "stand-alone" command that draws and fills a rectangle. So if you issue multiple fillRect
commands with multiple fillStyle
commands, each new rect will be filled with the preceeding fillstyle.
For a nicer effect, I recommend using strokeRect
instead of rect
, but that's your decision. Also, you may want to play with the condition from the while, to actually make them appear centered.
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");
var cornerpad = 0;
var rectwidth = 790;
var rectheight = 590;
function drawrectangles() {
ctx.beginPath();
ctx.rect(cornerpad, cornerpad, rectwidth, rectheight);
ctx.fillStyle = 'hsl(' + 360 * Math.random() + ', 50%, 50%)';
ctx.fill();
ctx.stroke();
}
while (rectheight > 5) {
rectheight -= 10;
rectwidth -= 10;
cornerpad += 10;
//console.log(`(h, w)=(${rectheight}, ${rectwidth})`);
drawrectangles();
}
canvas {
border: 1px dotted black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/canvasjs/1.7.0/canvasjs.js"></script>
<canvas id="canvas" width="790" height="590">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>
Edit:
I added a version that draws them much nicer, check it out :)
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");
var cornerpad = 0;
var rectwidth = 600;
var rectheight = 400;
var middleLine = rectheight / 2;
function drawrectangles() {
ctx.strokeRect(cornerpad, cornerpad, rectwidth, rectheight);
ctx.fillStyle = 'hsl(' + 360 * Math.random() + ', 50%, 50%)'
ctx.fillRect(cornerpad, cornerpad, rectwidth, rectheight);
}
while (cornerpad < middleLine) {
rectheight -= 20;
rectwidth -= 20;
cornerpad += 10;
//console.log(`(h, w)=(${rectheight}, ${rectwidth})`);
drawrectangles();
}
canvas {
border: 1px dotted black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/canvasjs/1.7.0/canvasjs.js"></script>
<canvas id="canvas" width="600" height="400">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>
Cheers!
Edit 2:
Because I was too absorbed by the =- 10
thing, I forgot to point out to actually use beginPath
and closePath
as functions and to call them as ctx.beginPath()
and ctx.closePath()
. Thanks to Kaiido for pointing that out and for the two working additional jsfiddles.