美文网首页
canvas画时钟

canvas画时钟

作者: 后简1994 | 来源:发表于2017-06-30 16:33 被阅读0次

    html:

    <canvas id="#clock" width="63px" height="63px"></canvas>

    js:

    var dom = $("#clock");

    var ctx = dom[0].getContext("2d");

    console.log(ctx.canvas.width);

    var width = ctx.canvas.width;

    var height = ctx.canvas.height;

    var r = width/2;

    var rem = width/200;

    function drawAround() {

    ctx.save();

    ctx.beginPath();

    ctx.translate(r,r);

    ctx.lineWidth = 2;

    ctx.arc(0,0,r-1,0,2*Math.PI,false);

    ctx.strokeStyle = "#FFF";

    ctx.stroke();

    for (var i = 0; i < 60; i++) {

    var rad = 2 * Math.PI/60 * i;

    var x = Math.cos(rad) * (r-6);

    var y = Math.sin(rad) * (r-6);

    ctx.beginPath();

    if (i % 5 != 0) {

    ctx.fillStyle = "rgba(255,255,255,0)";

    }

    else if (i % 3 != 0) {

    ctx.fillStyle = "#FFF";

    }

    else{

    ctx.fillStyle = "#F00";

    }

    ctx.arc(x,y,2,0,2*Math.PI,false);

    ctx.fill();

    }

    }

    function drawHour(hour,minute) {

    ctx.save();

    ctx.beginPath();

    var rad = 2 * Math.PI/12 * hour;

    var mrad = 2 * Math.PI/12/60 * minute;

    ctx.rotate(rad + mrad);

    ctx.lineWidth = 4;

    ctx.lineCap = "round";

    ctx.fillStyle = "#FFF";

    ctx.moveTo(0,3);

    ctx.lineTo(0,-14);

    ctx.stroke();

    ctx.restore();

    }

    function drawMinute(minute) {

    ctx.save();

    ctx.beginPath();

    var rad = 2 * Math.PI/60 * minute;

    ctx.rotate(rad);

    ctx.lineWidth = 3;

    ctx.lineCap = "round";

    ctx.moveTo(0,5);

    ctx.lineTo(0,-r+14);

    ctx.stroke();

    ctx.restore();

    }

    function drawSecond(second) {

    ctx.save();

    ctx.beginPath();

    var rad = 2 * Math.PI/60 * second;

    ctx.rotate(rad);

    ctx.fillStyle = "#F00";

    ctx.moveTo(-2,10);

    ctx.lineTo(2,10);

    ctx.lineTo(0,-r+10);

    ctx.lineTo(-1,-r+10);

    ctx.fill();

    ctx.restore();

    }

    function drawDot() {

    ctx.beginPath();

    ctx.fillStyle = "#FFF";

    ctx.arc(0,0,3,0,2*Math.PI,false);

    }

    function draw() {

    ctx.clearRect(0,0,width,height);

    var now = new Date();

    var hour = now.getHours();

    var minute = now.getMinutes();

    var second = now.getSeconds();

    drawAround();

    drawSecond(second);

    drawMinute(minute);

    drawHour(hour,minute);

    drawDot();

    ctx.restore();

    }

    draw();

    setInterval(draw,1000);

    相关文章

      网友评论

          本文标题:canvas画时钟

          本文链接:https://www.haomeiwen.com/subject/nrkicxtx.html