<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 RectWidth = 0 // 横幅
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.fillRect(CenterW - 260, CenterH - 160, RectWidth, 150)
ctx.fillStyle = 'rgba(232, 74, 95, 1)'
ctx.fillRect(CenterW - 200, CenterH - 100, RectWidth, 150)
ctx.fillStyle = 'rgba(42, 54, 59, 1)'
ctx.fillRect(CenterW - 140, CenterH - 40, RectWidth, 150)
if (RectWidth <= 400) {
RectWidth+=20
AnimateID = requestAnimationFrame(draw)
}
}
// スタートボタン
document.querySelector('#startBtn').addEventListener('click', () => {
if (!AnimateID) {
RectWidth = 0
AnimateID = requestAnimationFrame(draw)
}
})
// リセットボタン
document.querySelector('#resetBtn').addEventListener('click', () => {
AnimateID = null
RectWidth = 0
cancelAnimationFrame(AnimateID)
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.