我正在尝试使用HTML5 Canvas中的方块来构建金字塔,我有一个半工作的算法,唯一的问题是在三天之后并且缺乏数学能力我无法找到合适的公式.
这是我所拥有的,检查代码注释,以便您可以看到我们必须更改的算法的哪个部分.
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();
Run Code Online (Sandbox Code Playgroud)
这是在jsfiddle中工作的代码,所以我们可以尝试:
https://jsfiddle.net/g5spscpu/
期望的结果是:
好吧,如果有人能帮助我,我的大脑正在燃烧,我会很高兴.
您需要i在X位置的公式中使用索引:
W/2 - ((side / 2) + ((j - i/2) * side))
Run Code Online (Sandbox Code Playgroud)
请参阅https://jsfiddle.net/9esscdkc/
| 归档时间: |
|
| 查看次数: |
577 次 |
| 最近记录: |