HTML <canvas>
TAG는 JavaScript를 통해 다양한 그림을 그릴 수 있는 환경을 제공합니다.
<canvas>
TAG는 src 및 alt 속성이 없다는 점만 제외하면 img
요소 처럼 보입니다. canvas
TAG는 일반적인 이미지(margin, border, background...) 처럼 스타일 적용이 가능합니다.
<img>
TAG와 달리 <canvas>
TAG는 닫는 TAG </canvas>
가 필요합니다.
<canvas>
TAG는 <video>
, <audio>
, <picture>
처럼 <img>
와 달리, 인터넷 익스플로러 9이하 버전이나 텍스트기반 브라우저 등과 같은 캔버스를 지원하지 않는 오래된 브라우저를 위한 대체 컨텐츠를 정의하기 쉽습니다.
대체 콘텐츠를 정의하는 방법은 <canvas>
TAG안에 콘텐츠를 삽입합니다. <canvas>
TAG를 지원하지 않는 브라우저는 컨테이너를 무시하고 내부의 대체 콘텐츠를 렌더링합니다.
<canvas id="stockGraph" width="150" height="150">
current stock price: $3.15 +0.15
</canvas>
<canvas id="clock" width="150" height="150">
<img src="images/clock.png" width="150" height="150" alt=""/>
</canvas>
캔버스는 처음에는 비어있습니다. 무언가를 표시하기 위해서, 어떤 스크립트가 랜더링 컨텍스트에 접근하여 그리도록 할 필요가 있습니다. <canvas>
TAG는 getContext()
를 이용해서, 랜더링 컨텍스트와 그리기 함수를 사용 가능합니다. 2D 그래픽의 경우 CanvasRenderingContext2D
를 얻기위해 "2D"로 지정합니다.
var canvas = document.getElementById('tutorial');
var ctx = canvas.getContext('2d');
대체 컨텐츠는 <canvas>
를 지원하지 않는 브라우저에 표시됩니다. 스크립트 역시 getContext()
를 이용해서 이용해서 메소드 존재 여부를 테스트하므로써 프로그래밍 방식으로 지원하는지 확인이 가능합니다.
var canvas = document.getElementById('tutorial');
if (canvas.getContext){
var ctx = canvas.getContext('2d');
// drawing code here
} else {
// canvas-unsupported code here
}
경로는 점들의 집합이며 선의 한 부분으로 연결되어 여러가지 도형, 곡석을 이루고 두께와 색을 나타내게 됩니다.
ctx.strokeStyle
선 색상 지정
ctx.lineWidth
선 두께 지정
ctx.beginPath();
새로운 경로를 만들기. 경로를 만드는 첫번째 단계
ctx.moveTo(x,y);
선을 시작하는 좌표(좌표로 경로를 그리지 않고 이동하는 좌표)
ctx.lineTo(x,y);
선을 끝내는 좌표(현재 좌표에서 마지막 생성된 좌표로 선을 연결)
ctx.stroke();
선 그리기
let painting = false;
let filling = false;
function startPainting() {
painting = true;
}
function stopPainting() {
painting = false;
}
function onMouseMove(event) {
const x = event.offsetX;
const y = event.offsetY;
if (!painting) {
ctx.beginPath();
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
ctx.stroke();
}
}
if (canvas) {
canvas.addEventListener("mousemove", onMouseMove);
canvas.addEventListener("mousedown", startPainting);
canvas.addEventListener("mouseup", stopPainting);
canvas.addEventListener("mouseleave", stopPainting);
}