怎么用js输出一个菱形

JavaScript031

怎么用js输出一个菱形,第1张

方法有很多,我用HTML5的canvas写一个,你直接copy然后创建一个HTML文件,用google浏览器或者火狐亦或是高版本的IE打开就可以看到了

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title></title>

<style type="text/css">

body{

margin: 0

padding: 0

}

#myCanvas{

margin:200px 600px

border:5px solid #9c9898

}

</style>

<script type="text/javascript">

window.onload = function(){

var canvas = document.getElementById("myCanvas")

var context = canvas.getContext("2d")

drawLine(context,250,10,490,250,20,"blue","round")

drawLine(context,490,250,250,490,20,"blue","round")

drawLine(context,250,490,10,250,20,"blue","round")

drawLine(context,10,250,250,10,20,"blue","round")

}

function drawLine(context,startX,startY,endX,endY,lineWidth,strokeStyle,lineCap){

context.beginPath()

context.moveTo(startX,startY)

context.lineTo(endX,endY)

context.lineWidth = lineWidth

context.strokeStyle = strokeStyle

context.lineCap = lineCap

context.stroke()

}

</script>

</head>

<body>

<canvas id="myCanvas" width="500" height="500"></canvas>

</body>

</html>

代码如下,你要的菱形

<HTML>

<HEAD>

<TITLE>New Document </TITLE>

<script>

function draw(){

var line = parseInt(document.getElementById("myvalue").value)

var lineTemp = line%2

if(0==lineTemp){

alert("函数必须是奇数")

return

}

lineTemp = parseInt(line/2)

alert("line="+line+" lineTemp="+lineTemp)

var strArr = new Array()

for(var i=0i<lineTempi++){

for(var j=0j<linej++){

if(((j+i)==lineTemp)||((j-i)==lineTemp)){

strArr.push("*")

}else{

strArr.push(" ")

}

}

strArr.push("<br>")

}

for(var i=lineTempi<linei++){

for(var j=0j<linej++){

if(((j+i)==3*lineTemp)||((i-j)==lineTemp)){

strArr.push("*")

}else{

strArr.push(" ")

}

}

strArr.push("<br>")

}

document.getElementById("mydiv").innerHTML = strArr.join('')

}

</script>

</HEAD>

<BODY>

请输入奇数:<input type="text" value="3" id="myvalue">

<input type="button" onclick="draw()" value="show">

<div id="mydiv"></div>

</BODY>

</HTML>