HTML의
<canvas>
태그와 Javascript를 사용하면 다양한 그래픽 요소를 만들 수 있다. 단순한 도형 그리기, 데이터 시각화, 애니메이션, 웹 게임 등을 만들 수 있다고 한다.
html에 캔버스 태그 작성하기
캔버스는 canvas 엘리먼트를 DOM으로 조작하는 방식으로 작성되므로 엘리먼트를 선택할 때 사용할 id를 작성해 주는 것이 좋다.
<canvas id="canvas">
캔버스를 지원하지 않는 브라우저에서는 캔버스 대신 태그 사이 내용이 표시된다.
</canvas>
Javascript를 사용하여 엘리먼트를 선택하기
const canvas = document.querySelector("#canvas");
캔버스의 너비와 높이 설정하기
캔버스의 너비와 높이를 설정해야하며 canvas의 태그 속성으로 설정하는 방법과 DOM으로 설정하는 방법이 있다. 설정하지 않을 경우에는 기본값으로 300픽셀 * 150픽셀 사이즈로 생성된다.
<canvas>
태그 속성으로 너비와 높이 설정 <canvas id="canvas" width="500" height="500"></canvas>
// 화면 크기에 맞춰서 설정
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 화면 크기를 가져와 비례하여 설정
canvas.width = window.innerWidth * 0.5;
canvas.height = window.innerHeight * 0.4;
// DOM으로 설정할 시, 픽셀 단위가 아닌 vw, vh로 단위값을 지정해도 설정이 가능
// 주의해야 할 점은 style 속성을 이용하여 크기에 변화를 주는 경우는 픽셀의 크기까지 해당 단위에 비례해 확대하는 개념이므로, 특정한 경우가 아니면 사용을 자제해야한다.
canvas.style.width = "50vw";
canvas.style.height = "50vh";
색칠된 사각형 그리기
ctx.fillStyle = 'green'
ctx.fillRect = (10, 10, 100, 50)
//
선으로 사각형 그리기
ctx.lineWidth = 3;
ctx.strokeStyle = "blue";
ctx.strokeRect(10, 10, 100, 50)
사각형으로 지우기
ctx.clearRect( 20, 20, 80, 30)
클릭할 때 캔버스 위에서의 마우스 위치를 구하려면, 화면에서의 마우스 위치에서 화면에서의 캔버스 위치를 빼면 된다.
화면상 마우스 위치를 구하는 이벤트 객체의 속성은 X좌표는 event.clientX, Y좌표는 event.clientY이다. 화면상 캔버스의 위치를 구하는 속성은 X좌표는 ctx.canvas.offsetLeft, Y좌표는 ctx.canvas.offsetTop이다. 여기서 ctx는 canvas.getContext("2d")담은 변수이다.
html 파일
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<canvas id="canvas" width="200" height="150"></canvas>
<script src="src/index.js"></script>
</body>
</html>
js 파일
const canvas = document.querySelector("#canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
canvas.onclick = function (event) {
const x = event.clientX - ctx.canvas.offsetLeft;
const y = event.clientY - ctx.canvas.offsetTop;
ctx.fillStyle = "green";
ctx.fillRect(x - 15, y - 15, 30, 30);
//클릭한 위치를 사각형의 정중앙에 오게 하려면 사각형크기/2만큼 좌표에서 빼주면 된다.
};
const canvas = document.querySelector("#canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
canvas.onclick = function (event) {
const x = event.clientX - ctx.canvas.offsetLeft;
console.log(ctx);
const y = event.clientY - ctx.canvas.offsetTop;
ctx.beginPath();
ctx.arc(x, y, 30, 0, 2 * Math.PI); // (x, y, 반지름, 시작 각도, 끝 각도)
// x, y는 원의 중심 좌표
ctx.fillStyle = "aliceblue"; // 원의 채우기 색상 설정
ctx.fill(); // 원을 채우기
ctx.strokeStyle = "cadetblue"; // 원의 테두리 색상 설정
ctx.lineWidth = 2; // 테두리 선의 너비 설정
ctx.stroke(); // 원의 테두리 그리기
};