www.luery.xyz
H5-Canvas动画 入门
时钟制作
效果图
主要是利用的Canvas控制操作
- 坐标变化
- translate – > 平移坐标系
- rotate – > 旋转坐标系
- scale – > 缩放,用的少
- 绘画环境操作
- save – > 保存Canvas的状态
- restore – > 恢复Canvas之前保存的状态
<!--
时钟
-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<canvas id="can" width="800" height="600"></canvas>
</body>
<script>
var can = document.getElementById("can");
var ctx = can.getContext("2d");
function clock() {
//底盘
ctx.beginPath();
ctx.lineWidth = 20;
ctx.strokeStyle = "black";
ctx.arc(0,0,220,0,2*Math.PI);
ctx.closePath();
ctx.stroke();
//画小时刻度
ctx.save();
for(var i = 0; i < 12; i++) {
ctx.beginPath();
ctx.lineWidth = 6;
ctx.strokeStyle = "black";
ctx.rotate(2*Math.PI/12);
ctx.moveTo(0,-200);
ctx.lineTo(0,-170);
ctx.stroke();
}
ctx.restore();
//画分钟刻度
ctx.save();
for(var i = 0; i < 60; i++) {
ctx.beginPath();
ctx.lineWidth = 3;
ctx.strokeStyle = "black";
ctx.rotate(2*Math.PI/60);
ctx.moveTo(0, -200);
ctx.lineTo(0, -185);
ctx.stroke();
}
ctx.restore();
//画数字
ctx.save();
ctx.beginPath();
ctx.font = "25px Verdana";
ctx.fillStyle = "black";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
var h = [0,4,5,6,7,8,9,10,11,12,1,2,3];
for(var i = 1; i <= 12; i++) {
// ctx.rotate(2*Math.PI/12);
//每次转的角度
var deg = 2 * Math.PI / 12 * i;
var x = Math.cos(deg) * (220 - 65);
var y = Math.sin(deg) * (220 - 65);
ctx.fillText(h[i], x, y);
}
ctx.closePath();
ctx.restore();
//获取当前时间
var oDate = new Date;
var hour = oDate.getHours();
var minutes = oDate.getMinutes();
var seconds = oDate.getSeconds();
if(hour > 12){
hour = hour - 12;
hour = hour + minutes/60;
}
minutes = minutes + seconds/60;
//时针
ctx.save();
ctx.beginPath();
ctx.rotate(hour*30*Math.PI/180);
ctx.strokeStyle = "#F0AD4E";
ctx.lineWidth = 5;
ctx.moveTo(0,20);
ctx.lineTo(0,-90);
ctx.stroke();
ctx.closePath();
ctx.restore();
//分针
ctx.save();
ctx.beginPath();
ctx.rotate(minutes*6*Math.PI/180);
ctx.strokeStyle = "#A2D866";
ctx.lineWidth = 5;
ctx.moveTo(0,20);
ctx.lineTo(0,-130);
ctx.stroke();
ctx.closePath();
ctx.restore();
//秒钟
ctx.save();
ctx.beginPath();
ctx.rotate(seconds*6*Math.PI/180);
ctx.strokeStyle = "#F44336";
ctx.lineWidth = 4;
ctx.moveTo(0,30);
ctx.lineTo(0,-150);
ctx.stroke();
ctx.closePath();
ctx.restore();
//中心圆
ctx.save();
ctx.globalCompositeOperation = "source-over";
ctx.beginPath();
ctx.fillStyle = "#60D9F8";
ctx.strokeStyle = "#00B7FF";
ctx.lineWidth = 3;
ctx.arc(0, 0, 8, 0, 2*Math.PI);
ctx.fill();
ctx.stroke();
ctx.closePath();
ctx.restore();
//标记时间
ctx.beginPath();
ctx.font = "26px 微软雅黑";
ctx.fillStyle = "red";
var h = oDate.getHours();
var m = oDate.getMinutes();
var s = oDate.getSeconds();
var hh = h > 9 ? h : ('0' + h);
var mm = m > 9 ? m : ('0' + m);
var ss = s > 9 ? s : ('0' + s);
ctx.fillText(hh+":"+mm+":"+ss,-50,300);
}
clock();
setInterval(function(){
ctx.clearRect(0,0,800,600);
ctx.save();
ctx.translate(250,250);
clock();
ctx.restore();
},1000);
</script>
</html>