canvas 태그
<head>
<style>
canvas {
border: 2px solid gray;
}
</style>
</head>
<body>
<canvas id="canvas" width="600" height="400"></canvas>
</body>
canvas.js
function canvasApp(){
const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d')
ctx.fillStyle = 'red'
ctx.fillRect(100, 100, 100, 50);
ctx.font = '30px Arial'
ctx.fillStyle = 'black'
ctx.fillText('hello canvas', 200, 50)
ctx.beginPath()
ctx.arc(200, 200, 100, 0, Math.PI * 2)
ctx.fillStyle = 'blue'
ctx.fill()
}
document.addEventListener('DOMContentLoaded', canvasApp)
window.onload = canvasApp
document.addEventListener('DOMContentLoaded', 함수)
둘은 같은 기능인데 후자를 더 선호한다.
차이점
onload는 함수를 하나만 지정할 수 있다.
addEventListener는 추가를 가능하다.
특별한 경우가 아니라면 후자 방식 사용하기
canvas 기능
ctx.fillRect(x, y, w, h) -> 채워진 사각형 그리기
x, y - 좌표
w, h - 크기
ctx.fillStyle -> 색상 변경
ctx.fillText(text, x, y, maxWidth) -> 글자 넣기
ctx.font -> 폰트 크기와 폰트 종류 설정
ctx.beginPath()
ctx.arc(x, y, radius, startAngle, endAngle, counterlockwise) -> 호
Math.PI * 2 => 360도