[HTML] Graphics

귤티·2025년 4월 19일

front

목록 보기
2/10

canvas 태그

  • 2D 그래픽
  • x, y 좌표계를 다룸
  • 기본적으로 스타일을 아무것도 갖고 있지 않음
<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 => 도구 상자의 개념

ctx.fillRect(x, y, w, h) -> 채워진 사각형 그리기
x, y - 좌표
w, h - 크기

ctx.fillStyle -> 색상 변경

ctx.fillText(text, x, y, maxWidth) -> 글자 넣기

  • maxWidth는 optional

ctx.font -> 폰트 크기와 폰트 종류 설정

원 그리기

ctx.beginPath()
ctx.arc(x, y, radius, startAngle, endAngle, counterlockwise) -> 호

  • counterlockwise는 optional, boolean, undefined

Math.PI * 2 => 360도

profile
취준 진입

0개의 댓글