H分形是由一個字母H演化出迷宮一樣場景的分形圖案,其構造程序是:取一個中心點(x,y),以此中心點繪制一條長為L的水平直線和兩條長為H的豎直直線,構成一個字母“H”的形狀;再以兩條豎直直線的上下共4個端點為中心點,分別繪制一條長為L/2的水平直線和兩條長為H/2的豎直直線;重復以上操作直至達到要求的層數,可以繪制出H分形圖案,如圖1所示,

圖1 H分形圖案的生成
H分形采用遞回程序易于實作,撰寫如下的HTML代碼,
<!DOCTYPE html>
<head>
<title>H分形</title>
</head>
<body>
<canvas id="myCanvas" width="500" height="500" style="border:3px double #996633;">
</canvas>
<script type="text/javascript">
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
ctx.strokeStyle = "red";
ctx.lineWidth = 3;
var maxdepth =4;
var curdepth = 0;
function drawH(x,y,length,hight)
{
curdepth++;
ctx.beginPath();
ctx.moveTo(x-length/2,y);
ctx.lineTo(x+length/2,y);
ctx.moveTo(x-length/2,y-hight/2);
ctx.lineTo(x-length/2,y+hight/2);
ctx.moveTo(x+length/2,y-hight/2);
ctx.lineTo(x+length/2,y+hight/2);
ctx.stroke();
if(curdepth <= maxdepth)
{
drawH(x-length/2,y-hight/2,length*0.5,hight*0.5);
drawH(x-length/2,y+hight/2,length*0.5,hight*0.5);
drawH(x+length/2,y-hight/2,length*0.5,hight*0.5);
drawH(x+length/2,y+hight/2,length*0.5,hight*0.5);
}
curdepth--;
}
drawH(250,250,240,180);
</script>
</body>
</html>
在瀏覽器中打開包含這段HTML代碼的html檔案,可以看到在瀏覽器視窗中繪制出的H分形圖案,如圖2所示,

圖2 遞回深度maxdepth =4的H分形
將H分形的生成程序進行動態展示,撰寫如下的HTML檔案,
<!DOCTYPE html>
<head>
<title>H分形</title>
</head>
<body>
<canvas id="myCanvas" width="500" height="500" style="border:3px double #996633;">
</canvas>
<script type="text/javascript">
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
ctx.strokeStyle = "red";
ctx.lineWidth = 3;
var maxdepth =0;
var curdepth = 0;
function drawH(x,y,length,hight)
{
curdepth++;
ctx.beginPath();
ctx.moveTo(x-length/2,y);
ctx.lineTo(x+length/2,y);
ctx.moveTo(x-length/2,y-hight/2);
ctx.lineTo(x-length/2,y+hight/2);
ctx.moveTo(x+length/2,y-hight/2);
ctx.lineTo(x+length/2,y+hight/2);
ctx.stroke();
if(curdepth <= maxdepth)
{
drawH(x-length/2,y-hight/2,length*0.5,hight*0.5);
drawH(x-length/2,y+hight/2,length*0.5,hight*0.5);
drawH(x+length/2,y-hight/2,length*0.5,hight*0.5);
drawH(x+length/2,y+hight/2,length*0.5,hight*0.5);
}
curdepth--;
}
function go()
{
ctx.clearRect(0,0,canvas.width,canvas.height);
drawH(250,250,240,180);
maxdepth++;
curdepth=0;
if (maxdepth>4)
{
maxdepth=0;
}
}
window.setInterval('go()', 1500);
</script>
</body>
</html>
在瀏覽器中打開包含這段HTML代碼的html檔案,在瀏覽器視窗中呈現出如圖3所示的H分形動態生成效果,
圖3 H分形圖案動態生成
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/45607.html
標籤:JavaScript
下一篇:前端 獲取手機及設備型別
