首页 > 代码库 > canvas绘制一定数目的圆(均分)

canvas绘制一定数目的圆(均分)

绘制多圆

2016年5月24日12:12:26

绘制一定数目(num)颜色随机的小圆,围成一个大圆。根据num完全自动生成,且小圆自动均分大圆路径(num≥20)。

效果:

技术分享

前置技能:(1).Canvas(2).勾股定理、余弦定理、斜率方程、象限、角度与弧度转换等数学知识

HTML:

<canvas id="canvas" width="900" height="680">您的浏览器太老,请使用新版谷歌或火狐浏览器访问!</canvas><script src="http://www.mamicode.com/canvas_circle.js"></script>
JS:

/** * Created by suwt on 2016/4/26. * 注释部分为一条动态射线 */window.onload = function () {    var canvas = document.getElementById(‘canvas‘);    var context = canvas.getContext(‘2d‘);    loadTeams(context);};var circle_x = 350, // 圆心坐标    circle_y = 350,    circle_r = 200, // 半径    team_num = 30, // 小圆数目    colors = ["#33B5E5","#0099CC","#AA66CC","#9933CC","#99CC00","#669900","#FFBB33","#FF8800","#FF4444","#CC0000"];  //随机颜色组//加载布局模拟图function loadTeams(cxt) {    cxt.beginPath();    cxt.strokeStyle = ‘green‘;    cxt.arc(circle_x, circle_y, circle_r, 0, 2 * Math.PI);    cxt.stroke();    cxt.closePath();    seating(cxt)    setInterval("seating(canvas.getContext(‘2d‘))",1000);}//分配小圆座次function seating(cxt) {    var angle = 360 / team_num; //角度    var team_x = 0, team_y = 0;    var team_r = team_num < 20 ? 30 : Math.sqrt(circle_r * circle_r * 2 * (1 - Math.cos(changeRadian(angle)))) / 2;  //余弦定理  计算小圆的最大半径     BC2=AB2+AC2-2×AB×AC×cosα  如果小圆数目小于20个,半径最大30(上限)    for (var i = 0; i < team_num; i < i++) {        team_x = circle_x + Math.sin(changeRadian(i * angle)) * circle_r;  //角度转弧度        team_y = circle_y - Math.cos(changeRadian(i * angle)) * circle_r;        cxt.beginPath();        //cxt.strokeStyle = ‘red‘;        cxt.arc(team_x, team_y, team_r, 0, 2 * Math.PI);        cxt.stroke();        //cxt.fillStyle = "rgb(0,102,153)";        cxt.fillStyle = colors[ Math.floor( Math.random()*colors.length ) ];        cxt.fill();        //cxt.closePath();    }    //x=358;    //y=358;    //drawLine(cxt,x,y);    //setInterval(function(){    //   x=x+1;    //    y=y+1;    //    drawLine(cxt,x,y);    //},5);    }//function drawLine(cxt,x,y) {//    console.log(x+"---"+y);//    //cxt.clearRect(0,0,1000,1000);//    cxt.beginPath();//    cxt.strokeStyle = "black";//    cxt.lineWidth = 2;//    cxt.moveTo(x, y);//    cxt.lineTo(x+1,y+1);//    cxt.stroke();//    cxt.closePath();//    //cxt.rotate((Math.PI/180)*15);//}//角度转换为弧度function changeRadian(angle) {    return Math.PI / 180 * angle;}



来自为知笔记(Wiz)


canvas绘制一定数目的圆(均分)