折腾了好久,总算改出来了
/**
* Created by Administrator on 2015-03-18.
*/
var WINDOW_WIDTH = 1024;
var WINDOW_HEIGHT = 768;
var RADIUS = 8;
var MARIN_TOP = 60;
var MARGIN_LEFT = 30;
//Date传值时注意,传入月份时要比实际传入的大一月份,eg:实际传入6月时,应传入5月
const endTime = new Date(2015,2,20,18,47,52);
var curShowTimeSeconds = 0;
//页面加载完后执行
window.onload = function(){
var canvas_t = document.getElementById("canvas");
var context_t = canvas_t.getContext("2d");
canvas_t.width = WINDOW_WIDTH;
canvas_t.height = WINDOW_HEIGHT;
curShowTimeSeconds = getCurrentShowTimeSeconds();
//render(context_t);
setInterval(
function(){
render(context_t);
update();
}
,50
);
}
/*获取时间差(单位:秒)*/
function getCurrentShowTimeSeconds(){
var curTime = new Date();
//获取当前时间距离截止时间的时间差(单位:毫秒)
//getTime(),返回距 1970 年 1 月 1 日之间的毫秒数
var ret = endTime.getTime() - curTime.getTime();
//Math.round(),把一个数字舍入为最接近的整数
ret = Math.round(ret/1000);
return ret >= 0 ? ret : 0;
}
/*时间刷新*/
function update(){
var nextShowTimeSeconds = getCurrentShowTimeSeconds();
var nextHours = parseInt(nextShowTimeSeconds / 3600);
var nextMinutes = parseInt((nextShowTimeSeconds - nextHours*3600) / 60);
var nextSeconds = nextShowTimeSeconds % 60;
if(nextSeconds != curShowTimeSeconds){
curShowTimeSeconds = nextShowTimeSeconds;
}
}
/*显示时间*/
function render(cxt){
//clearRect() 方法清空给定矩形内的指定像素
cxt.clearRect(0,0,WINDOW_WIDTH,WINDOW_HEIGHT);
var hours = parseInt(curShowTimeSeconds / 3600);
var minute = parseInt(curShowTimeSeconds - hours*3600) / 60;
var seconds = curShowTimeSeconds % 60;
/*最终显示为 12:34:56*/
//显示时钟
renderDigit(MARGIN_LEFT,MARIN_TOP,parseInt(hours/10),cxt);
renderDigit(MARGIN_LEFT+15*(RADIUS+1),MARIN_TOP,parseInt(hours%10),cxt);
//显示冒号:“:”
renderDigit(MARGIN_LEFT+30*(RADIUS+1),MARIN_TOP,10,cxt);
//显示分钟
renderDigit(MARGIN_LEFT+39*(RADIUS+1),MARIN_TOP,parseInt(minute/10),cxt);
renderDigit(MARGIN_LEFT+54*(RADIUS+1),MARIN_TOP,parseInt(minute%10),cxt);
//显示冒号:“:”
renderDigit(MARGIN_LEFT+69*(RADIUS+1),MARIN_TOP,10,cxt);
//显示秒钟
renderDigit(MARGIN_LEFT+78*(RADIUS+1),MARIN_TOP,parseInt(seconds/10),cxt);
renderDigit(MARGIN_LEFT+93*(RADIUS+1),MARIN_TOP,parseInt(seconds%10),cxt);
}
//参数含义:1.数字距离左侧的距离。2.数字距离上边的距离。3.要显示的数字。4.显示数字
function renderDigit(x,y,num,cxt){
cxt.fillStyle = "rgb(0,102,153)";
for(var i=0; i<digit[num].length; i++)
for(var j=0; j<digit[num][i].length; j++)
if(digit[num][i][j] == 1){
cxt.beginPath();
cxt.arc(x+j*2*(RADIUS+1)+RADIUS+1,y+i*2*(RADIUS+1)+RADIUS+1,RADIUS,0,2*Math.PI);
cxt.closePath();
cxt.fill();
}
}