【关键点】
齿轮数组的建立、旋转角度的调整。
【图例】
【代码】
<!DOCTYPE html>
<html lang="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<head>
<title>双“方齿齿轮”啮合示意图</title>
<style type="text/css">
.centerlize{
margin:0 auto;
width:1200px;
}
</style>
</head>
<body onload="init();">
<div class="centerlize">
<canvas id="myCanvas" width="512px" height="512px" style="border:1px dotted black;">
如果看到这段文字说您的浏览器尚不支持HTML5 Canvas,请更换浏览器再试.
</canvas>
</div>
</body>
</html>
<script type="text/javascript">
<!--
/*****************************************************************
* 将全体代码(从<!DOCTYPE到script>)拷贝下来,粘贴到文本编辑器中,
* 另存为.html文件,再用chrome浏览器打开,就能看到实现效果。
******************************************************************/
// canvas的绘图环境
var ctx;
// 边长
const WIDTH=1000;
const HEIGHT=500;
// 舞台对象
var stage;
//-------------------------------
// 初始化
//-------------------------------
function init(){
// 获得canvas对象
var canvas=document.getElementById('myCanvas');
canvas.width=WIDTH;
canvas.height=HEIGHT;
// 初始化canvas的绘图环境
ctx=canvas.getContext('2d');
ctx.translate(WIDTH/2,HEIGHT/2);// 原点平移到画布中央
// 准备
stage=new Stage();
stage.init();
// 开幕
animate();
}
// 播放动画
function animate(){
stage.update();
stage.paintBg(ctx);
stage.paintFg(ctx);
// 循环
if(true){
window.requestAnimationFrame(animate);
}
}
// 舞台类
function Stage(){
// 转角
this.angle=0;
// 准备齿轮数组
this.gearArr=[];
// 初始化
this.init=function(){
for(var i=0;i<36;i++){
var theta=Math.PI/18*i-Math.PI/36;
var x1=150*Math.cos(theta);
var y1=150*Math.sin(theta);
var x2=140*Math.cos(theta);
var y2=140*Math.sin(theta);
if(i%2==0){
this.gearArr.push({x:x1,y:y1});
this.gearArr.push({x:x2,y:y2});
}else{
this.gearArr.push({x:x2,y:y2});
this.gearArr.push({x:x1,y:y1});
}
}
}
// 更新
this.update=function(){
this.angle+=Math.PI/180;
}
// 画背景
this.paintBg=function(ctx){
ctx.clearRect(-WIDTH/2,-HEIGHT/2,WIDTH,HEIGHT);// 清屏
}
// 画前景
this.paintFg=function(ctx){
// 画黄齿轮
ctx.save();
ctx.translate(-150,0);
ctx.rotate(-this.angle);
ctx.beginPath();
for(var i=0;i<this.gearArr.length;i++){
ctx.lineTo(this.gearArr[i].x,this.gearArr[i].y);
}
ctx.closePath();
ctx.fillStyle="yellow";
ctx.fill();
ctx.font="30px consolas";
ctx.textAlign="center";
ctx.textBaseLine="Middle";
ctx.fillStyle="white";
ctx.fillText("逆火原创",0,0);
ctx.restore();
// 画紫齿轮
ctx.save();
ctx.translate(140,0);
ctx.rotate(this.angle+Math.PI/18);
ctx.beginPath();
for(var i=0;i<this.gearArr.length;i++){
ctx.lineTo(this.gearArr[i].x,this.gearArr[i].y);
}
ctx.closePath();
ctx.fillStyle="purple";
ctx.fill();
ctx.font="30px Arial";
ctx.textAlign="center";
ctx.textBaseLine="Middle";
ctx.fillStyle="white";
ctx.fillText("逆火原创",0,0);
ctx.restore();
}
}
/*---------------------------------------------
风雪压我两三年,我笑风轻雪如棉。
----------------------------------------------*/
//-->
</script>
END