雑多なブログ

音楽や語学、プログラム関連の話題について書いています

Canvasの練習で時計を作ってみた。

めちゃくちゃしょぼいけど、とりあえずCanvasの練習で時計らしきものを作ってみた。

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>時計</title>
<script>
var ctx;

function init() {
    ctx = document.getElementById("graph").getContext('2d');
    paint();
    setInterval(paint, 1000);
}

function drawLine(x0, y0, x1, y1, color, line_width) {
    ctx.strokeStyle = color;
    ctx.beginPath();
    ctx.lineWidth = line_width;
    ctx.moveTo(x0, y0);
    ctx.lineTo(x1, y1);
    ctx.closePath();
    ctx.stroke();
}

function paint() {
    ctx.fillStyle = 'white';
    ctx.fillRect(0, 0, 400, 400);
    ctx.save();

    ctx.translate(145, 130);
    ctx.beginPath();
    ctx.arc(0, 0, 100, 0, Math.PI * 2);
    ctx.closePath();
    ctx.stroke();

    var d = new Date(),
        degree_s = (d.getSeconds() * 6) - 90,
        degree_m = (d.getMinutes() * 6) - 90,
        degree_h = (d.getHours() * 30) - 90;

    drawLine(0, 0, cos(degree_s) * 95, sin(degree_s) * 95, "gray", 1);
    drawLine(0, 0, cos(degree_m) * 80, sin(degree_m) * 80, "#666", 4);
    drawLine(0, 0, cos(degree_h) * 70, sin(degree_h) * 70, "black", 7);

    ctx.restore();
}

const sin = (degree) => Math.sin(degree * Math.PI / 180).toFixed(3);
const cos = (degree) => Math.cos(degree * Math.PI / 180).toFixed(3);
</script>
</head>
<body onload="init()" style="margin:0;padding:0">
<canvas id="graph" width="290" height="260"></canvas>
</body>
</html>