JSFiddle - React, Tailwind, and code Playground
by secretgspot
HTML
<canvas id="canvas" width="300" height="300"></canvas>
CSS
canvas {
border: solid 1px;
}
JavaScript
var DrawClockHand = function(cv) {
if( !cv.getContext ) return null;
this._cv = cv;
this._ctx = cv.getContext('2d');
this.TIME = 1000;
this._r = 50;
}
DrawClockHand.prototype.setPosition = function(x,y) {
x = x || 0;
y = y || 0;
this._x = x;
this._y = y;
}
DrawClockHand.prototype.toPosition = function() {
this._ctx.translate(this._x, this._y);
}
DrawClockHand.prototype.setRadius = function(r) {
this._r = r;
}
DrawClockHand.prototype.run = function() {
var that = this;
(function() {
var now = new Date();
var hour = now.getHours();
var min = now.getMinutes();
var sec = now.getSeconds();
var hDeg = 360/12*hour;
var mDeg = 360/60*min;
var sDeg = 360/60*sec;
//現在のcanvasの状態を保存
that._ctx.save();
//描画クリア
that._ctx.beginPath();
that._ctx.clearRect(0,0,that._cv.width,that._cv.height);
//指定位置に移動
that.toPosition();
//中心点を描画
that.drawDot();
//メモリを描画
that.drawMemory(30,that._r);
//数字を描画
that.drawNumber();
//短針を描画 (角度,長さ,太さ)
that.setHand(hDeg,that._r*0.6,6);
//長針を描画 (角度,長さ,太さ)
that.setHand(mDeg,that._r*0.8,4);
//秒針を描画 (角度,長さ,太さ)
that.setHand(sDeg,that._r,2);
//canvasの状態を元に戻す
that._ctx.restore();
setTimeout(arguments.callee, that.TIME);
})();
}
DrawClockHand.prototype.drawNumber = function() {
for( var i=1; i<=12; i++ ) {
this._ctx.save();
this._ctx.fillStyle = '#111';
this._ctx.rotate((360/12*i)*Math.PI/180);
this._ctx.translate(0,-(this._r+20));
this._ctx.rotate(-((360/12*i)*Math.PI/180));
this._ctx.textAlign = 'center';
this._ctx.fillText(i,0,0);
this._ctx.restore();
}
}
DrawClockHand.prototype.setHand =...