canvas画时钟

2017-06-30  本文已影响0人  后简1994

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);

上一篇 下一篇

猜你喜欢

热点阅读