<div id="contents"></div>
body {
margin: 0;
padding: 0;
}
#contents {
width: 100vw;
height: 100vh;
}
// Canvas追加
const target = document.getElementById('contents') // 追加先
const CreateCanvas = document.createElement('canvas') // canvas element作成
CreateCanvas.setAttribute('id', 'canvas') // canvas に id 付与
target.appendChild(CreateCanvas) // 追加
function draw() {
// 追加先のサイズ取得
let Cwidth = target.clientWidth
let Cheight = target.clientHeight
// Canvas サイズ設定
CreateCanvas.width = Cwidth
CreateCanvas.height = Cheight
// Canvas・コンテキスト取得
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')
// Canvasの中央取得
let CenterW = Cwidth/2
let CenterH = Cheight/2
// 描画リセット
ctx.clearRect(0, 0, Cwidth, Cheight)
// 円描画
ctx.fillStyle = 'rgba(42, 54, 59, 1)'
ctx.strokeStyle = 'rgba(232, 74, 95, 1)'
ctx.beginPath()
ctx.arc(CenterW - 10, CenterH - 10, 120, 0, Math.PI * 2, true)
ctx.fill()
ctx.beginPath()
ctx.arc(CenterW + 10, CenterH + 10, 120, 0, Math.PI * 2, true)
ctx.stroke()
// ランダムで衛星生成
ctx.beginPath()
ctx.arc(CenterW + Math.floor(Math.random() * 30) - 150, CenterH + Math.floor(Math.random() * 30) - 150, Math.floor(Math.random() * 50) + 10, 0, Math.PI * 2, true)
ctx.fill()
ctx.beginPath()
ctx.arc(CenterW + Math.floor(Math.random() * 30) - 150, CenterH + Math.floor(Math.random() * 30) - 150, Math.floor(Math.random() * 50) + 10, 0, Math.PI * 2, true)
ctx.stroke()
ctx.beginPath()
ctx.arc(CenterW + Math.floor(Math.random() * 30) + 120, CenterH + Math.floor(Math.random() * 30) + 120, Math.floor(Math.random() * 50) + 10, 0, Math.PI * 2, true)
ctx.stroke()
// テキスト描画
ctx.fillStyle = 'rgba(232, 74, 95, 1)'
ctx.strokeStyle = 'rgba(255,255,255, 1)'
ctx.font = '42px serif'
// テキストサイズ取得
let textSize = ctx.measureText('Text Test')
// テキスト塗りつぶし
ctx.fillText('Test Text', CenterW - (textSize.width / 2) -10, CenterH - 10)
// テキストアウトライン
ctx.strokeText('Test Text', CenterW - (textSize.width / 2) + 10, CenterH + 10)
}
// 画面リサイズ時再描画
window.onresize = draw
// 初回描画
draw()
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.