본문 바로가기

프론트앤드 수업

[javascript] canvas 사용해보기

728x90

canvas

  1. html에 canvas태그 추가하기

    canvas에 너비와 높이가 지정되지 않으면 300px 150px로 자동지정

  2. javascript - getContext()메서드
    캔버스의 드로잉 컨텍스트를 반환해줌

1) 사각형 그리기
fillRect(x,y,width,height) 채워진 사각형 그리기
strikeRect(x,y,width,height) 선으로된 사가형 그리기
clearRect(x,y,width,height) 지정된 사각형 영역을 지움

       let canvas = document.querySelector('#canvas');
        let ctx = canvas.getContext('2d');
        //면 색상 지정
        ctx.fillStyle = 'green';
        //사각형을 만들어줌 (x좌표,y좌표,x크기,y크기)
        ctx.fillRect(10,10,100,100);
        ctx.strokeStyle = 'red'
        // 선으로된 사각형
        ctx.strokeRect(200,200,50,50);
        // 해당 위치만큼만 지워준다. 지우개툴
        ctx.clearRect(10,10,50,50);

2)패스그리기
beginPath() 새 경로를 만듬
closePath() 마지막 위치에서 시작 위치를 연결
stroke() 윤곽선 그리기
fill() 칠하기
moveTo(x,y) 지정된 위치에서 시작한다.(펜툴의 시작점)
lineTo(x,y) x,y좌표까지 선을 그린다. (다음 점)

 //패스를 시작(펜도구 선택)
        ctx.beginPath();
        //시작 위치- 처음 점 찍기
        ctx.moveTo(50,50);
        //선그리기 - 다음 점 찍기
        ctx.lineTo(150,50);
        ctx.lineTo(150,150);
        // 선 종료 및 선그리기
        // closePath시 2줄이 그려진상태에서 처음줄로 그대로 이어줌(펜툴과 같다.)
        ctx.closePath();
        // stroke()시 줄을 그어주고 fill로 사용시 면을 칠해준다.    
        ctx.stroke();

삼각형이 그려짐

3)호(arc) 그리기
arc(x,y,radius,startAngle,endAngle,anticlockwise)
라디안 각도(1PI가 180도)
Math.PI * 2 ==> 360도

  ctx.beginPath();
        ctx.arc(100,100,100,0,Math.PI*2,true);
        ctx.moveTo(180,100);
        ctx.arc(100,100,80,0,Math.PI,false);
        ctx.stroke();

4) 선과 면 스타일 지정
lineWidth 선의 두께를 지정
fillStyle 면색을 지정
strokeStyle 선색을 지정
lineCap 선의 끝점 모양을 결정
butt, round, square - > defult = butt

  let lineCap = ['butt','round','suqare'];
            for(let i=0;i<10;i++){
                ctx.lineWidth = 1+i;
                ctx.lineCap = lineCap[i%3];
                ctx.beginPath();
                ctx.moveTo(5+i*16,5);
                ctx.lineTo(5+i*16,140);
                ctx.stroke();
            }

5) 이미지 적용
* 이미지 객체 만들기
cunst img = document.createElemant('img');
const img = new image();
img.src = './abc.jpg'
* 캔버스에 이미지 그리기
ctx.drawimage(image, dx, dy, width, height)

        // 객체만들기 1. cunst img = document.createElemant('img');
        // const image = document.querySelector('#source');
        // image.addEventListener('load', e=>{
        //     ctx.drawImage(image,50,100,100,150);
        // })
        // 객체만들기 2. const img = new image();
        const imgElem = new Image();
        imgElem.src ='https://mdn.mozillademos.org/files/5397/rhino.jpg'
        imgElem.addEventListener('load', ()=>{
            ctx.drawImage(imgElem,50,50);
            ctx.drawImage(imgElem,200,50,100,60);
            ctx.drawImage(imgElem,400,100,300,300);

6) 애니메이션
window.rquestAnimationFrame(); - 비동기 함수
css의 transition으로 처리하기 어려운 애니메이션이나,
html5의 canvas, SVG 등의 애니메이션 구현을 위하여 사용됨
모든 애니메이션을 직접 프레임 단위로 계산을 함

setInterval -> 스스로 반복해서 호출(o)
requestAnimationFrame() -> 스스로 반복해서 호출(x)
재귀적으로 window.requestAnimationFrame() 함수를 다시 호출해야함
function frame(){
window.requestAnimationFrame(frame);
}

concelAnimationFrame(변수명)

728x90
댓글