单击按钮创建金字塔

时间:2017-07-17 08:35:41

标签: javascript

我想从for循环中创建一个piramid。

我目前的结果是这样的

enter image description here

我希望像这样

enter image description here

<button id="piramid" onclick="piramid()">test</button>

继承人的代码

https://jsfiddle.net/k22bf4o4/

如何循环以使结果变得像最后一张图像? 谢谢你的时间

1 个答案:

答案 0 :(得分:0)

以前的评论者说你不应该在StackOverflow上发布你的作业。也就是说,这是一个有趣的运动,我想为自己做。

对于数字,我现在看到数字来自两行高的金字塔,它们是颠倒的。例如。从顶部取第三行:1 + 2 = 3其中3将是倒置金字塔的顶部,基线为1和2(行上方有3行)。一旦你看到了,就由你或其他人来为它编写代码。

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Pyramid</title>
</head>

<body></body>

<script src="pyramid.js"></script>

</html>

pyramid.js

let blockWidth = 20,
    blockHeight = 20,
    blockCountBaseRow = 10,
    blockOffset = blockWidth / 2;
let drawSurfaceWidth = blockWidth * blockCountBaseRow,
    drawSurfaceHeight = blockHeight * blockCountBaseRow,
    drawSurfaceCenter = drawSurfaceWidth / 2;

createDrawingSurface();
drawPyramid();

function createDrawingSurface() {
    let body = document.getElementsByTagName('body').item(0);
    body.innerHTML += '<div id="drawingSurface" style="' +
        'position:absolute;' +
        'width:' + drawSurfaceWidth + 'px;' +
        'height:' + drawSurfaceHeight + 'px;' +
        'background:#EEE;">' +
        '</div>';
}

function drawPyramid() {
    for (let row = 1; row < blockCountBaseRow + 1; row++) {
        let left = calculateLeftFirstBlock(row);
        let top = calculateTop(row);
        for (let j = 1; j < row + 1; j++) {
            addBlock(left, top);
            left += blockWidth;
        }
    }
}

function addBlock(left, top) {
    let drawingSurface = document.getElementById("drawingSurface");
    drawingSurface.innerHTML += '<div style="' +
        'position:absolute;' +
        'left:' + left + 'px;' +
        'top:' + top + 'px;' +
        'width:' + blockWidth + 'px;' +
        'height:' + blockHeight + 'px;' +
        'border:1px solid black; ' +
        'background:#DDD;">' +
        '</div>';
}

function calculateLeftFirstBlock(row) {
    return drawSurfaceCenter - blockOffset * row;
}

function calculateTop(row) {
    return (row - 1) * blockHeight;
}
相关问题