Canvas
[Canvas] 보일러 플레이트 작성 (캔버스 클래스)
gamzaggang7
2024. 5. 24. 15:23
728x90
index.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./style.css">
<title>Document</title>
</head>
<body>
<canvas></canvas>
</body>
<script type="module" src="./index.js"></script>
</html>
CanvasOption.js
export default class canvasOption {
constructor() {
this.canvas = document.querySelector('canvas')
this.ctx = this.canvas.getContext('2d')
this.dpr = window.devicePixelRatio
this.fps = 60
this.interval = 1000 / this.fps
this.canvasWidth = innerWidth
this.canvasHeight = innerHeight
}
}
index.js
import canvasOption from "./CanvasOption.js"
class Canvas extends canvasOption {
constructor() {
super()
}
init() {
this.canvasWidth = innerWidth
this.canvasHeight = innerHeight
this.canvas.width = this.canvasWidth * this.dpr
this.canvas.height = this.canvasHeight * this.dpr
this.ctx.scale(this.dpr, this.dpr)
this.canvas.style.width = this.canvasWidth + 'px'
this.canvas.style.height = this.canvasHeight + 'px'
}
render() {
let now, delta
let then = Date.now()
const frame = () => {
requestAnimationFrame(frame)
now = Date.now()
delta = now - then
if (delta < this.interval) return
// code write here
then = now - (delta % this.interval)
}
requestAnimationFrame(frame)
}
}
const canvas = new Canvas()
window.addEventListener('load', () => {
canvas.init()
canvas.render()
})
window.addEventListener('resize', () => {
canvas.init()
})
style.css
html, body {
margin: 0;
width: 100%;
height: 100%;
overflow: hidden;
}
728x90