clock.js
var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); var clockImage = new Image(); var clockImageLoaded = false; clockImage.onload = function () { clockImageLoaded = true; } clockImage.src = 'images/clock.jpg'; function addBackgroundImage() { //画图,中心点移到了canvas当中,所以画图开始位置变成了-200、-200 context.drawImage(clockImage, canvas.width / 2 * -1, canvas.height / 2 * -1, canvas.width, canvas.height); } function drawHourHand(theDate) { var hours = theDate.getHours() + theDate.getMinutes() / 60; var degrees = (hours * 360 / 12) % 360; context.save(); context.fillStyle = 'black'; context.rotate(degreesToRadians(degrees)); drawHand(110, 7); context.restore(); } function drawMinuteHand(theDate) { var minutes = theDate.getMinutes() + theDate.getSeconds() / 60; context.save(); context.fillStyle = 'black'; context.rotate(degreesToRadians(minutes * 6)); drawHand(130); context.restore(); } function drawSecondHand(theDate) { context.save(); context.fillStyle = 'red'; var seconds = theDate.getSeconds(); context.rotate(degreesToRadians(seconds * 6)); drawHand(150); context.restore(); } function drawHand(size, thickness) { thickness = thickness || 4; context.beginPath(); context.moveTo(0, 0); // center context.lineTo(thickness * -1, -10); context.lineTo(0, size * -1); context.lineTo(thickness, -10); context.lineTo(0, 0); context.fill(); } function writeBrandName() { } function createClock() { addBackgroundImage(); var theDate = new Date(); drawHourHand(theDate); drawMinuteHand(theDate); drawSecondHand(theDate); } function clockApp() { if (!clockImageLoaded) { setTimeout('clockApp()', 100); return; } //把旋转中心放到canvas的当中 context.translate(canvas.width / 2, canvas.height / 2); setInterval('createClock()', 1000); } function degreesToRadians(degrees) { return (Math.PI / 180) * degrees; }展示效果