HTML 5 canvas+js画时钟
创建 Canvas 元素(画布)
向 HTML5 页面添加 canvas 元素。
规定元素的 id、宽度和高度:
<canvas id="canvas" width="500" height="500"></canvas>
通过 JavaScript 来绘制
<script>
var canvas=document.getElementById("canvas");
var context=canvas. getContext("2d");
绘制钟表边框
var width=canvas.width;
var height=canvas.height;
var r=width/2;
function fun(){
context.save()
context.translate(r,r);/*注意:定义时钟整体圆形坐标圆点*/
context.beginPath();
context.arc(0,0,r-5,0,2*Math.PI,false);
context.closePath();
context.lineWidth = 10;
context.strokeStyle="aqua"
context.stroke();
绘制表盘数字
var hoursnum=[3,4,5,6,7,8,9,10,11,12,1,2]
context.font = "18px Arial"; /*(字体修饰)*/
context.textAlign = "center";/*(整体位置修饰)*/
context.textBaseline = "middle";/*(整体位置修饰)*/
for(var i=0;i<hoursnum.length;i++){
var rad=2*Math.PI/12*i;
var x=Math.cos(rad)*(r-30);
var y=Math.sin(rad)*(r-30);
context.fillText(hoursnum[i],x,y)
}
绘制表盘刻度点(循环添加区分刻度类型、三角函数关系获取X、Y坐标点)
for(var j=0;j<60;j++){
var rad=2*Math.PI/60*j;
var x=Math.cos(rad)*(r-15);
var y=Math.sin(rad)*(r-15);
context.beginPath();
if(j % 5===0){
context.fillStyle="#000"
}else{
context.fillStyle="#ccc"
}
context.arc(x,y,2,0,2*Math.PI)
context.closePath();
context.fill()
}
}
绘制时针
function drawHour(hour,minu){
context.save();
context.beginPath();
var rad = Math.PI * 2 / 12 * hour;
var rad_minu = Math.PI * 2 / 12 / 60 * minu;
context.rotate(rad + rad_minu)
context.lineWidth=5;
context.moveTo(0,10);
context.lineTo(0,-r/2);
context.lineCap="round";
context.stroke()
context.restore()
}
绘制分针
function drawMinu(minu){
context.save();
context.beginPath();
context.lineWidth=4;
var rad = Math.PI * 2 / 60 * minu;
context.rotate(rad)
context.moveTo(0,10);
context.lineTo(0,-r+50);
context.lineCap="round";
context.strokeStyle="aquamarine";
context.stroke()
context.restore()
}
绘制秒针
function drawMiao(miao){
context.save();
var rad = Math.PI * 2 / 60 * miao;
context.beginPath();
context.rotate(rad)
context.fillStyle = "#f00";
context.moveTo(-2,20);
context.lineTo(2,20);
context.lineTo(1,-r+20);
context.lineTo(-1,-r+20);
context.closePath()
context.fill()
context.restore()
}
绘制时钟中心固定点
function Dian(){
context.beginPath();
context.arc(0,0,4,0,2*Math.PI);
context.fillStyle="#ccc";
context.closePath()
context.fill()
}
追加定时器函数调用整体呈现
function draw(){
context.clearRect(0,0,width,height);
var datenow = new Date();
var hour = datenow.getHours();
var minu =datenow.getMinutes();
var miao= datenow.getSeconds();
fun()
drawHour(hour,minu)
drawMinu(minu)
drawMiao(miao)
Dian()
context.restore()
}
draw()
setInterval(draw,1000)/*无限定时器*/
</script>