<canvas 태그> 에 JS 펜으로 그림 그리기
< canvas 태그 >
- 브라우저 화면에 canvas를 깔고,
=> 그 위에, 삼각형 원 글씨 이미지등을
JavaScript 를 사용해 그려낸다.
1. 캔버스 만들기 - id / width / height 필수
: HTML <body>에서 태그로 만들고
<canvas id="a" width="500px" height="300px" >
( style=border 줘서 영역 표시해서 사용하면 편함 )
2. 캔버스랑 펜 준비
: <script> 에서 그린다.
let paper = document.getElementById("a"); //캔버스
let pen = paper.getContext("2d"); // 펜
- 사실상 2d 만 거의 사용 (소문자 d)
3. 붓으로 그리기
- 사각형메소드 ( x, y, width, height )
: 왼쪽부터x 위쪽부터 y, 가로 세로길이
pen.strokeRect(50, 50, 100, 100);
pen.fillRect(200, 50, 100, 100);
- 선긋기 메소드 => 삼각형
pen.beginPath();
pen.moveTo(60, 10);
- 켄버스 이 위치로 이동해줘
pen.lineTo(110, 100);
- 이 위치까지 선 그어줘
pen.lineTo(10, 100);
- 그 다음 이 위치까지 선 그어줘 (순서)
pen.closePath();
- 이제 beginPath로 연결해줘
pen.stroke(); / fill();
- 선 / 채워짐
- 텍스트 메소드
pen.font = "40px serif";
pen.strokeText("Hello CanvasTest", 300, 200);
pen.fillText("Hello CanvasTest", 300, 200);
- 이미지 메소드
( 이미지 가져와서 펜으로 꾸미고 그걸 사용하고자 할때 )
- 기본 onload 로 함수화해서 사용
=> 사진 다 로드 되면 화면에 보여줌
그리기
pen.drawImage(이미지, x위치, y위치, width, height );
복사
let copy =
pen.getImageData( 켄버스 x위치, y위치에서, width50, height50 복사 );
붙여넣기
pen.putImageData(복사이미지, x위치, y위치에 붙여넣기 )
let myimg = new Image();
myimg.src="chtml5.jpg";
myimg.onload = function(){
pen.drawImage(myimg, 400, 10, paper.width/3, paper.height/3);
let copy = pen.getImageData(400,10, 100, 100);
pen.putImageData( copy, 200, 100);
}
- canvas Style 꾸미기
(canvas 안의 stroke,fill 형태의 모든 개체에 적용)
pen.strokeStyle ="red";
pen.lineWidth = 5;
- stroke 에만 적용
pen.fillStyle="yellow";
[[ 캔버스 패턴 정리 ]]
<canvas id="mycanvas" width=600 height=600 style="border:2px solid yellow"></canvas>
// 이미지 크기 조절
mycanvas.width = myimage.width;
mycanvas.height = myimage.height;
//종이-펜 만들고
var mycanvas = document.getElementById("mycanvas");
var pencil = mycanvas.getContext("2d");
//사진 가져오고
var myimage = new Image();
myimage.src = "/naverai/${param.textimage}";
myimage.onload = function(){
pencil.drawImage(myimage,0,0, myimage.width, myimage.height);
//사각형그리기
pencil.strokeStyle = "red";
pencil.lineWidth = 1;
pencil.strokeRect(x1,y1,width1, height1);
//글씨쓰기
pencil.font="15px";
pencil.fillStyle="navy";
pencil.fillText( Text, x1, y1);
//네모점찍기
pencil.fillRect( (x1+x2)/2, (y1+y2)/2, 10,10);
}