以前、時計の針が動くものを Canvas で作ったのですが、コードが長くて冗長な感じになってしまいました。
もっと短くできるだろうと思い、挑戦してみました。
コードをシンプルにする
↓clockhand_canvas.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(() => { | |
let canvas = null; | |
let ctx = null; | |
let cx, cy; | |
let hand_length; | |
let angle, rad; | |
window.addEventListener( | |
'load', | |
() => { | |
initialize(); | |
render(); | |
}, | |
false | |
); | |
function initialize() { | |
canvas = document.getElementById('canvas'); | |
canvas.width = window.innerWidth; | |
canvas.height = window.innerHeight; | |
ctx = canvas.getContext('2d'); | |
} | |
function render() { | |
// background | |
ctx.fillStyle = 'gray'; | |
ctx.fillRect(0, 0, canvas.width, canvas.height); | |
// center point | |
cx = canvas.width / 2; | |
cy = canvas.height / 2; | |
// clock hand | |
clockHand(new Date().getHours() * 30 - 90, 100); | |
clockHand(new Date().getMinutes() * 6 - 90, 150); | |
clockHand(new Date().getSeconds() * 6 - 90, 250); | |
// animation | |
window.requestAnimationFrame(render); | |
} | |
function clockHand(rad, hand_length) { | |
angle = (Math.PI / 180) * rad; | |
ctx.beginPath(); | |
ctx.moveTo(cx, cy); | |
ctx.lineTo( | |
cx + Math.cos(angle) * hand_length, | |
cy + Math.sin(angle) * hand_length | |
); | |
ctx.stroke(); | |
} | |
})(); |
時計の針の動作を以下にまとめてみました。
function clockHand(rad, hand_length) { angle = (Math.PI / 180) * rad; ctx.beginPath(); ctx.moveTo(cx, cy); ctx.lineTo( cx + Math.cos(angle) * hand_length, cy + Math.sin(angle) * hand_length ); ctx.stroke(); }
そして、それぞれの針の数値はrenderの以下の部分に設定しています。
clockHand(new Date().getHours() * 30 - 90, 100); clockHand(new Date().getMinutes() * 6 - 90, 150); clockHand(new Date().getSeconds() * 6 - 90, 250);
シンプルにしたつもりなのですが、おそらく全然シンプルじゃないですね。。
もっと勉強して、さらに改善できるようにします。