I'm trying to build a pyramid using squares in HTML5 Canvas, I have an algoritm that is half working, the only problem is that after three days and some lack of math abilities I haven't been able to find the proper formula.
Here is what I have, check the code comments so you can see what part of the algorithm we have to change.
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var W = 1000; var H = 600;
var side = 16;
canvas.width = W;
canvas.height = H;
function square(x, y) {
ctx.fillStyle = '#66FF00';
ctx.fillRect(x, y, side, side);
ctx.strokeStyle = '#000';
ctx.strokeRect(x, y, side, side);
}
function draw() {
ctx.fillRect(0, 0, W, H);
ctx.save();
for(var i = 0; i < 30; i++) {
for(var j = 0; j < i + 1; j++) {
square(
//Pos X
//This is what we have to change to
//make it look like a pyramid instead of stairs
W / 2 - ((side / 2) + (j * side)),
//Pos Y
side * (i + 1)
);
}
}
ctx.restore();
}
//STARTS DRAWING
draw();
This is the code working in jsfiddle so we can try it:
https://jsfiddle.net/g5spscpu/
The desired result is:
Well, I would love if someone could give me a hand, my brain is burning.
You need to use the i
index in the formula for X position with:
W/2 - ((side / 2) + ((j - i/2) * side))
see https://jsfiddle.net/9esscdkc/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With