用javascirpt画个太极

偶然看到用代码画太极,感觉很有趣,用JS写了一个

过程很简单,画了张图,应该一看就懂了

代码也很简单,如下,注释很多

function TaiJi(r,canvas){
	this.r = r;
	this.ctx = canvas.getContext("2d");
	
	var width = canvas.clientWidth, height = canvas.clientHeight;
	this.ctx.translate( width/2, height/2);
}

TaiJi.prototype.draw = function(){
	var ctx = this.ctx;
	var r = this.r;
	
	//一.画左边半个白圈
	ctx.beginPath();
	ctx.arc(0,0,this.r,1.5*Math.PI,0.5*Math.PI);
	ctx.fillStyle = "#fff";
	ctx.fill();
	
	//二.右边单个黑圈
	ctx.beginPath();
	ctx.arc(0,0,r,0.5*Math.PI,1.5*Math.PI);
	ctx.fillStyle = "#000";
	ctx.fill();

	//以半径的一半为新的半径,在中心线上下1/4处各画两个半圆
	var r2 = r/2;
	
	//三.上边小半圆
	ctx.beginPath();
	//理论上只要半圆就好,不过如果实际只画半圆的话,不是很贴,会有一道不明显的细缝,所以画了整个圆
	ctx.arc(0,-r2,r2,0,2*Math.PI);
	ctx.fillStyle = "#fff";
	ctx.fill();
	
	//四.下边小半圆
	ctx.beginPath();
	//理论上只要半圆就好,不过如果实际只画半圆的话,不是很贴,会有一道不明显的细缝,所以画了整个圆
	ctx.arc(0,r2,r2,0*Math.PI,2*Math.PI); 
	ctx.fillStyle = "#000";
	ctx.fill();

	//画两个“眼睛”,具体长度应该是多少我也不知道
	//这里定为半径的1/5,看起来比较像了,不纠结了
	//圆心就是三,四两步里面的圆心
	var r3 = r / 5
	
	//五.上方黑色“眼睛”
	ctx.beginPath();
	ctx.arc(0,-r2,r3,0,2*Math.PI);
	ctx.fillStyle = "#000";
	ctx.fill();

	//六.下方白色“眼睛”
	ctx.beginPath();
	ctx.arc(0,r2,r3,0,2*Math.PI);
	ctx.fillStyle = "#fff";
	ctx.fill();
}

//让太极旋转
TaiJi.prototype.rotate = function(interval){
	var self = this;
	setInterval(function(){
		self.ctx.rotate( 0.5 * Math.PI/180);
		self.draw();
	},interval);
}

/*****************************************/

var taiji = new TaiJi(200, document.getElementById('myCanvas') );
taiji.rotate(30);

  

效果如下,一个旋转的太极(看不到的可以更新浏览器了,程序员怎么能用这么老的浏览器):

后来无聊又改成了八卦

 
原文地址:https://www.cnblogs.com/varlxj/p/taiji.html