2017-07-17 5 views
-2

私はforループからpiramidを作成します。ボタンをクリックするとpiramidが作成されます

私の現在の結果は、私はHERESにこの

enter image description here

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

コードのようになりたい、この

enter image description here

のようなものです

https://jsfiddle.net/k22bf4o4/

どのようにループすると、結果は最後のイメージのようになりますか? お時間をいただきありがとうございます

+1

だからあなたの質問は何ですか? – Alex

+0

私は説明を更新します – GerryofTrivia

+4

これは宿題のようです。あなた自身でそれを解決する必要があります! –

答えて

0

上記のコメントは、あなたの宿題をStackOverflowに投稿しないでください。それは私が自分のためにやりたかった楽しい運動です。

数字については、数字が上下2桁のピラミッドに由来することがわかりました。例えば。上から3番目の行を取る: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; 
} 
関連する問題