您的位置:首页 > 其它

谢尔宾斯基三角垫

2015-12-21 23:33 253 查看
使用混沌描点的方法画出来的,很神奇。以下是网页代码,只能在支持html5的浏览器上看。

<html>
<canvas id="blackboard" width="1000" height="1000">
</canvas>
<script>
function draw()
{
// 获取画布
var canv = document.getElementById("blackboard");
var context = canv.getContext("2d");

// 获得像素数组
var bitArray = context.getImageData(0, 0, 1000, 1000);

// unit是二分之一的边长
var unit = 500;

// 随便定义一个初始点
var startPointX = 550;
var startPointY = 800;

for(var i=0; i< 100000; i++)
{
// 生成一个随机数
var sNum = Math.floor(Math.random()*3);

// 定义要画的点
var tempPointX;
var tempPointY;

// A点坐标是(unit, 0)
if(sNum == 0)
{
tempPointX = Math.round(unit + (startPointX-unit)/2);
tempPointY = Math.round(0 + (startPointY-0)/2);
}
// B点坐标是(2*unit, 根号3*unit)
else if(sNum == 1)
{
tempPointX = Math.round(2*unit + (startPointX-2*unit)/2);
tempPointY = Math.round(Math.sqrt(3)*unit + (startPointY-Math.sqrt(3)*unit)/2);
}
// C点坐标是(0, 根号3*unit)
else if(sNum == 2)
{
tempPointX = Math.round(0 + (startPointX-0)/2);
tempPointY = Math.round(Math.sqrt(3)*unit + (startPointY-Math.sqrt(3)*unit)/2);
}

// 在这个坐标上画蓝色点
bitArray.data[(1000*tempPointY + tempPointX)*4] = 0;
bitArray.data[(1000*tempPointY + tempPointX)*4+1] = 0;
bitArray.data[(1000*tempPointY + tempPointX)*4+2] = 255;
bitArray.data[(1000*tempPointY + tempPointX)*4+3] = 255;

// 迭代
startPointX = tempPointX;
startPointY = tempPointY;
}

// 提交到画布
context.putImageData(bitArray, 0, 0);
}

window.addEventListener("load", draw, true);
</script>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: