canvas画时钟

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Cnavas绘制时钟 背景图的绘制(大圆、数字、小圆点),掌握基础知识:圆的绘制(arc方法),关于圆的弧度的计算...
    Iris_mao阅读 2,518评论 7 26
  • 一:canvas简介 1.1什么是canvas? ①:canvas是HTML5提供的一种新标签 ②:HTML5 ...
    GreenHand1阅读 4,724评论 2 32
  • 一、canvas简介 1.1 什么是canvas?(了解) 是HTML5提供的一种新标签 Canvas是一个矩形区...
    Looog阅读 3,973评论 3 40
  • 一、canvas简介 1.1 什么是canvas?(了解) 是HTML5提供的一种新标签 Canvas是一个矩形区...
    J_L_L阅读 1,560评论 0 4
  • 啥是canvas? HTML5 标签用于绘制图像(通过脚本,通常是 JavaScript)。不过, 元素本身...
    kiaizi阅读 796评论 0 4