2017-07-17 4 views
-2

ich möchte eine piramid aus For-Schleife erstellen.erstellen piramid, wenn Sie auf eine Schaltfläche klicken

mein aktuelles Ergebnis ist wie dieser

enter image description here

Ich mag dieses

sein wollen

enter image description here

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

heres den Code

https://jsfiddle.net/k22bf4o4/

wie Schleife, so wird das Ergebnis wie das letzte Bild werden? Vielen Dank für Ihre Zeit

+1

So Ihre Frage, was ist? – Alex

+0

ich aktualisiere die Beschreibung – GerryofTrivia

+4

sieht aus wie Hausaufgaben. Sie sollten es selbst lösen! –

Antwort

0

Die vorherigen Kommentatoren haben Recht, dass Sie Ihre Hausaufgaben nicht auf StackOverflow posten sollten. Das ist eine lustige Übung, die ich selbst machen wollte.

Für die Zahlen sehe ich jetzt, dass die Zahlen von Pyramiden aus zwei Reihen hoch, die auf den Kopf gestellt sind, stammen. Z.B. nimm die dritte Reihe von oben: 1 + 2 = 3, wobei die 3 die Spitze der umgekehrten Pyramide mit der Basisreihe 1 und 2 ist (die Reihe über der Reihe mit 3). Sobald Sie das sehen, liegt es an Ihnen oder jemand anderem in SO, Code dafür zu schreiben.

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; 
} 
Verwandte Themen