运行效果截图如下:
具体代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>canvas绘制矩形</title>
<script type="text/javascript" >
function draw(id) {
var canvas = document.getElementById("canvas")
if (canvas) {
var context = canvas.getContext("2d")
context.fillStyle = "#DDDDDD"
context.fillRect(0, 0, 400, 400)
context.strokeStyle = "black"
context.fillStyle = "gray"
context.lineWidth = 5
context.fillRect(0,0,200,300)
context.strokeRect(0,0,200,200)
} else {
return
}
}
function drawBorder(id) {
var canvas = document.getElementById("canvas2")
if (canvas) {
var context = canvas.getContext("2d")
context.fillStyle = "red"
context.strokeStyle = "black"
context.lineWidth = 5
context.fillRect(0,0, 300, 200)
context.strokeRect(0,0,300,200)
} else {
return
}
}
window.onload = function () {
draw("canvas")
drawBorder("canvas2")
}
</script>
</head>
<body>
<canvas id="canvas" width="400" style="background:red" height="400"></canvas>
<hr />
<canvas id="canvas2" width="400" height="400"></canvas>
</body>
</html>
首先要明确,在JavaScript里面没有二维数组的概念,只能用普通数组来模拟出二维数组的效果。其次,对二维数组进行分析,可以得出循环的次数的规律,即偶数/2或者奇数对2取整后加1。
再次,可以看出方阵是从右下角开始,逆时针逐渐增加得来。
那么,可以写出以下函数:
function
printAll(number
,start){
//number为N阶矩阵,start为开始的数字,默认值分别是5和1。
number
=
number
||
5
start
=
start
||
1
//
c为求出的循环次数
var
c
=
number%2
==
0
?
number/2
:
Math.ceil(number/2)
//
定义一个一维数组,方便生成二维数组
var
arr
=
[]
//
生成二维数组并初始化,值为0
for(
var
i
=
0
i
<
number
i++){
arr[i]
=
[]
for(var
j
=
0
j
<
number
j++){
arr[i].push(0)
}
}
//
循环一次的函数
function
circle(c){
//
从下往上赋值
for(
i
=
number
-
c
-
1
i
>=
c
i--){
arr[i][number
-
c
-
1]
=
start++
}
//
从右往左赋值
for(i
=
number
-
c
-
2
i
>=
c
i--){
arr[c][i]
=
start++
}
//
从上往下赋值
for(
i
=
c
+
1
i
<
number
-
c
i++){
arr[i][c]
=
start++
}
//
从左往右赋值
for(i
=
c
+
1
i
<
number
-c
-
1
i++){
arr[number
-
c
-
1][i]
=
start++
}
}
//
循环给数组赋值
for(j
=
0
j
<
c
j++){
circle(j)
}
//
在控制台查看生成的数组信息,可注释掉
for(
i
=
0
i
<
number
i++){
console.log(arr[i])
}
}
希望可以帮到你,思路和函数全给你了
test:function(){
varballoonPurpleObj =this.balloonPurple.getBoundingBox()
//var tonguePlateObj = this.tonguePlate.getBoundingBox()
vardrawNode =newcc.DrawNode()
drawNode.clear()//清除节点缓存
drawNode.ctor()//构造函数
drawNode.drawRect(cc.p(balloonPurpleObj.x,balloonPurpleObj.y),cc.p(balloonPurpleObj.x+balloonPurpleObj.width,balloonPurpleObj.y+balloonPurpleObj.height),cc.color(180,180,180))
drawNode.setZOrder(100)
this.addChild(drawNode)//加入Layer层
},