p5.js と JavaScript の Canvas を勉強しています。
今回は、デジタル時計を作ってみました。
▼ p5.js 版
p5.jsは少し勉強していたことがあったので、それほど苦労しなかったのですが、1桁だった場合の「0」の入れ方はもう少し良いやり方があると思います。
↓p5js.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 jikoku_hour, jikoku_minute, jikoku_second; | |
let posX, posY; | |
function setup() { | |
createCanvas(640, 320, P2D); | |
} | |
function draw() { | |
background(200, 100); | |
jikoku_hour = hour(); | |
jikoku_minute = minute(); | |
jikoku_second = second(); | |
posX = 100; | |
posY = 160; | |
textSize(60); | |
// hour | |
if (jikoku_hour < 10) { | |
text('0' + jikoku_hour + ':', posX, posY); | |
} else { | |
text(jikoku_hour + ':', posX, posY); | |
} | |
// minute | |
if (jikoku_minute < 10) { | |
text('0' + jikoku_minute + ':', posX + 100, posY); | |
} else { | |
text(jikoku_minute + ':', posX + 100, posY); | |
} | |
// second | |
if (jikoku_second < 10) { | |
text('0' + jikoku_second, posX + 100 * 2, posY); | |
} else { | |
text(jikoku_second, posX + 100 * 2, posY); | |
} | |
} |
▼ Canvas 版
Canvasは難しいですね。
普通のJavaScriptなので、JavaScriptの知識が必要なことが多く調べることが多いです。
↓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; | |
window.addEventListener( | |
'load', | |
() => { | |
initialize(); | |
render(); | |
}, | |
false | |
); | |
function initialize() { | |
canvas = document.body.querySelector('canvas'); | |
ctx = canvas.getContext('2d'); | |
} | |
function render() { | |
ctx.fillStyle = 'gray'; | |
ctx.fillRect(0, 0, 640, 320); | |
let date = new Date(); | |
ctx.font = '64px Courier New'; | |
ctx.fillStyle = 'black'; | |
let posY = 160; | |
// hours | |
if (date.getHours() < 10) { | |
ctx.fillText('0' + date.getHours() + ':', 100, posY); | |
} else { | |
ctx.fillText(date.getHours() + ':', 100, posY); | |
} | |
// minutes | |
if (date.getMinutes() < 10) { | |
ctx.fillText('0' + date.getMinutes() + ':', 220, posY); | |
} else { | |
ctx.fillText(date.getMinutes() + ':', 220, posY); | |
} | |
// seconds | |
if (date.getSeconds() < 10) { | |
ctx.fillText('0' + date.getSeconds(), 330, posY); | |
} else { | |
ctx.fillText(date.getSeconds(), 330, posY); | |
} | |
console.log(date.getHours(), date.getMinutes(), date.getSeconds()); | |
window.requestAnimationFrame(render); | |
} | |
})(); |
CanvasをやることでJavaScriptの知識も増えそうなので、主にCanvasをがんばっていこうと思います。