JSFiddle - React, Tailwind, and code Playground

by secretgspot

HTML

<canvas id="canvas" width="300" height="300"></canvas>

CSS

canvas {
    border: solid 1px;
}

JavaScript

//時計の針を描くクラス。引数に描画するcanvas要素を取ります。。
var DrawClockHand = function(cv) {
    if( !cv.getContext ) return null;
    this._cv = cv;
    this._ctx = cv.getContext('2d');
    this._x = 0;
    this._y = 0;
};

DrawClockHand.prototype.setPosition = function(x,y) {
    x = x || 0;
    y = y || 0;
    this._x = x;
    this._y = y;
};

DrawClockHand.prototype.movePosition = function() {
    this._ctx.setTransform(1,0,0,1,this._x,this._y);
};

DrawClockHand.prototype.run = function() {    
    var now = new Date();
    var hour = now.getHours() % 12;
    var min = now.getMinutes();
    var sec = now.getSeconds();
    
    //時間から時計の角度を計算
    var hDeg = 360/12*hour;
    var mDeg = 360/60*min;
    var sDeg = 360/60*sec;
    
    //描画位置を初期化
    this.movePosition();
    
    //短針を描画
    this.setHand(hDeg,40,6);
    
    //長針を描画
    this.setHand(mDeg,80,4);
    
    //秒針を描画
    this.setHand(sDeg,100,2);
};

DrawClockHand.prototype.setHand = function(deg,size,base) {
    size = size || 40;
    base = base || 4;
    deg = deg || 0;
    
    this._ctx.save();
    
    //針の回転。ラジアンで与える
    this._ctx.rotate(deg*Math.PI/180);
    
    this.draw(size,base);
    this._ctx.restore();
};

DrawClockHand.prototype.draw = function(size,base) {
    this._ctx.save();
    
    //針の色
    this._ctx.fillStyle = '#333';
    
    //針の描画
    this._ctx.translate(-base/2, 0);
    this._ctx.moveTo(0, 0);
    this._ctx.lineTo(base/2, -size);
    this._ctx.lineTo(base, 0);
    this._ctx.closePath();
    this._ctx.fill();
    
    this._ctx.restore();
};

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

//時計の針クラスのインスタンスを生成
var dch = new DrawClockHand(canvas);
dch.setPosition(canvas.width/2, canvas.height/2);

(function() {
    //描画クリア
    ctx.beginPath();
    ctx.setTransform(1,0,0,1,0,0);
    ctx.clearRect(0,0,canvas.width,canvas.height);
    
    dch.run();
    setTimeout(arguments.callee, 1000);
})();