<div id="contents">
<button id="startBtn">Start</button>
<button id="resetBtn">Reset</button>
</div>
body {
margin: 0;
padding: 0;
}
#contents {
position: relative;
width: 100vw;
height: 100vh;
}
#contents button {
position: absolute;
top: 10px;
width: 100px;
height: 50px;
border-radius: 3px;
border: none;
cursor: pointer;
}
#startBtn {
left: 120px;
}
#resetBtn {
left: 10px;
}
// Canvas追加
const target = document.getElementById('contents') // 追加先
const CreateCanvas = document.createElement('canvas') // canvas element作成
CreateCanvas.setAttribute('id', 'canvas') // canvas に id 付与
target.appendChild(CreateCanvas) // 追加
let AnimateID // ID
let canvas
let ctx
let Cwidth
let Cheight
function draw() {
// 追加先のサイズ取得
Cwidth = target.clientWidth
Cheight = target.clientHeight
// Canvas サイズ設定
CreateCanvas.width = Cwidth
CreateCanvas.height = Cheight
// Canvas・コンテキスト取得
canvas = document.getElementById('canvas')
ctx = canvas.getContext('2d')
// Canvasの中央取得
let CenterW = Cwidth/2
let CenterH = Cheight/2
// 描画リセット
ctx.clearRect(0, 0, CenterW, CenterH)
// 矩形の塗りつぶし描画
ctx.fillStyle = 'rgba(42, 54, 59, 1)'
ctx.beginPath()
ctx.moveTo((CenterW - 50) + Math.floor(Math.random() * 10) - 5, (CenterH + 70) + Math.floor(Math.random() * 10) - 5)
ctx.lineTo((CenterW + 50) + Math.floor(Math.random() * 10) - 5, (CenterH + 70)+ Math.floor(Math.random() * 10) - 5)
ctx.lineTo(CenterW + Math.floor(Math.random() * 10) - 5, (CenterH - 70) + Math.floor(Math.random() * 10) - 5)
ctx.shadowBlur = 15
ctx.shadowColor = 'rgba(42, 54, 59, 1)'
ctx.fill()
// 輪郭描画の色指定 / 矩形の輪郭描画
ctx.strokeStyle = 'rgba(232, 74, 95, 1)'
ctx.beginPath()
// パス生成
for (let i = -200; i <= 200; i += 5) {
if (i == -200) {
ctx.moveTo(CenterW + i, CenterH + (Math.floor(Math.random() * 100) - 50))
} else {
ctx.lineTo(CenterW + i, CenterH + (Math.floor(Math.random() * 100) - 50))
}
}
// 描画
ctx.stroke()
AnimateID = requestAnimationFrame(draw)
}
// スタートボタン
document.querySelector('#startBtn').addEventListener('click', () => {
if (!AnimateID) {
RectWidth = 0
AnimateID = requestAnimationFrame(draw)
}
})
// リセットボタン
document.querySelector('#resetBtn').addEventListener('click', () => {
cancelAnimationFrame(AnimateID)
AnimateID = null
Cwidth = target.clientWidth
Cheight = target.clientHeight
canvas = document.getElementById('canvas')
ctx = canvas.getContext('2d')
// ctx.clearRect(0, 0, Cwidth, Cheight)
})
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.