canvas绘制正多边形

<!DOCTYPE html>
<html>
<head>
<title>html拖拽事件</title>
<script src='../js/jquery-1.8.3.js' type="text/javascript"></script>
<script src='../js/need_1.js' type="text/javascript"></script>
<script src='../js/need_2.js' type="text/javascript"></script>
<style type="text/css">
#canvas_dom{background-color: #FFFFF0}
</style>
</head>
<body>
<div>
<canvas id="canvas_dom" width="500px" height="500px"></canvas>
</div>
</body>
<script type="text/javascript">
var canvas_dom = document.getElementById("canvas_dom");
var ctx = canvas_dom.getContext('2d');




//绘制正多边形()
function draw(ctx,n){
ctx.save();
//绘制坐标轴
ctx.beginPath();
ctx.moveTo(0,250);
ctx.lineTo(500,250);
ctx.closePath();
ctx.stroke();


ctx.beginPath();
ctx.moveTo(250,0);
ctx.lineTo(250,500);
ctx.closePath();
ctx.stroke();


ctx.translate(250,250);//将坐标轴移动到中心点
var all_angle = 360*(Math.PI/180);//将角度转化为弧度
var unit_angle = all_angle/n;//每一个角度是多少弧度
var init_angle = 0;



ctx.beginPath();
for(var i = 0;i < n;i ++){
init_angle = i*unit_angle;
var pos_x = Math.cos(init_angle)*180;
var pos_y = Math.sin(init_angle)*180;
ctx.lineTo(pos_x,pos_y);
}
ctx.closePath();
ctx.stroke();
ctx.restore();
}
//自执行函数
(function(){
draw(ctx,10);
})();
</script>
</html>

猜你喜欢

转载自blog.csdn.net/wdhouyigege/article/details/80452246