当前位置:首页 > 自己看书写了一个最简单的时钟,后续会更新美化后的,canvas时钟效果(一)

自己看书写了一个最简单的时钟,后续会更新美化后的,canvas时钟效果(一)

发布于 2019-02-20 阅读 298 次 Canvas HTML5

代码应该还是比较容易看懂的。

初始的一些准备

var canvas = document.getElementById('canvas');
    context = canvas.getContext('2d'),
    FONT_HEIGHT = 15,
    MARGIN = 35,
    HAND_TRUNCATION = canvas.width/25,
    HOUR_HAND_TRUNCATIO = canvas.width/10,
    NUMBER_SPACING = 20,
    RADIUS = canvas.width/2 - MARGIN,
    NUMBER_RADIUS = RADIUS + NUMBER_SPACING;

canvas.width = 600;
canvas.height = 300;
context.font = FONT_HEIGHT + 'px Arial';
// context.textBaseline = 'middle';

绘制表盘的外部圆形

function drawCircle(){
    context.beginPath();
    context.arc(canvas.width/2, canvas.height/2, RADIUS, 0 ,Math.PI*2, true);
    context.stroke();
}

绘制表盘数字


function drawNumberals(){
    var numberals = [1,2,3,4,5,6,7,8,9,10,11,12],
        angle = 0,
        numberalWidth = 0;
    numberals.forEach(function(numberal){
        angle = Math.PI/6 *(numberal-3);
        numberalWidth = context.measureText(numberal).width;
        context.fillText(numberal, canvas.width/2+Math.cos(angle)*NUMBER_RADIUS-numberalWidth/2, canvas.height/2+Math.sin(angle)*NUMBER_RADIUS+FONT_HEIGHT/2);
    })
}

绘制表盘中间的圆形点

function drawCenter(){
    context.beginPath();
    context.arc(canvas.width/2, canvas.height/2, 10, 0 ,Math.PI*2, true);
    context.fill();
}

绘制指针

/**
* loc Number 12小时时间
* isHour Boolean 是否是时针
*/
function drawHand(loc, isHour){
    var angle = Math.PI*2*loc/60 - Math.PI/2,
        hand_radius = isHour ? RADIUS - HAND_TRUNCATION - HOUR_HAND_TRUNCATIO : RADIUS - HAND_TRUNCATION;
    context.beginPath();
    context.moveTo(canvas.width/2, canvas.height/2);
    context.lineTo(canvas.width/2+Math.cos(angle)*hand_radius, canvas.height/2+Math.sin(angle)*hand_radius);
    context.stroke();
}

绘制所有指针

function drawHands(){
    var date = new Date(),
        hour = date.getHours();
    hour = hour > 12 ? hour - 12 : hour; //24时转12时
    drawHand(hour*5 + date.getMinutes()/60*5, true); //这里要注意一下,小时和分钟的转换关系
    drawHand(date.getMinutes(), false);
    drawHand(date.getSeconds(), false);
}

绘制钟表

function drawClock(){
    context.clearRect(0, 0, canvas.width, canvas.height);
    drawCircle();
    drawNumberals();
    drawCenter();
    drawHands();
}

让表针动起来

setInterval(drawClock, 1000);
drawClock();