본문 바로가기
방송대_HTML5

HTML5_6강) 캔버스(2)

by dot_Connector 2021. 9. 22.

*여기에 있는 내용은 제가 복습차,  방송대 컴퓨터 과학과 HTML5 이관용 교수님의 PPT 수업 내용을 참조하여 정리함을 알립니다. 

 

1) 스타일 지정하기

 

1-1) 선스타일

 

<선 스타일 관련 속성>

  • strokeStyle - 선의 색상(또는 그라데이션, 패턴 지정)
  • lineWidth- 선의 두께 지정(기본 1픽셀)

 

 

  • lineJoin [=bevel | round | miter(기본) ]

- 두 선이 만나 꺽이는 모서리 부분의 모양 지정

  • lineCap [ =butt (기본) | round | square ]

- 선의 양쪽 끝부분의 모양 지정

- square의 경우, 선의 두께 절반 만큼 양쪽으로 늘어난 것

 

 

ctx.beginPath();

ctx.strokeStyle = 'rgba(255, 0, 255, 0, 5)';

ctx.lineWidth = 30;

ctx.lineJoin = 'bevel';

ctx.lineCap ='round';

ctx.moveTo(50,50);

ctx.linTo(200, 250);

ctx.lineTo(250, 120);

ctx.stroke();

 

 

1-2)  점선그리기

  • SetLineDash() 메서드 

- 원하는 점선의 패턴을 설정하는 메서드

- 인자 -> 패턴으로 그려지는 부분과 그려지지않는 부분이 반복되는 배열

ctx.beginPath();

ctx.setLineDash([10]);

ctx.arc(150,150,100,0.2*Math.PI);

ctx.stroke();

 

ctx.beginPath();

ctx.lineWidth=10;

ctx.setLineDash([1,2,3,4]);

ctx.rect(30,30,240,240);

ctx.stroke();

 

 

ctx.beginPath(); // Path 로 도형 그리기

ctx.setLineDash([5,2]);  // 점선 크기 및 간격 설정

ctx.fillStyle="lightblue"; //사각형 색깔 설정

ctx.rect(100,100,100,100); // 사각형 그리기(투명하게)

ctx.stroke(); // 사각형 눈에 보이게 그리기

ctx.fill(); // 사각형 하늘색으로 채우기 

 

1-3) 채우기 스타일

  • fill() 메서드를 사용하는 경우

- stroke() -> strokeStyle vs. fille() -> ??? 속성

  •  속성

- fillStyle - 도형을 채우는 색상이나 스타일 지정

- globalAlpha - 색상의 투명도 지정, 값 -> 0.0 (완전 투명) ~ 1.0 (완전 불투명)

 

<fillStyle 속성>

 

 

ctx.lineWidth = 20;

ctx.strokStyle = "blue";

ctx.strokeRect(50, 50, 100, 100);

ctx.fillStyle = "red";

ctx.fillRect(50,50,100,100); 

 

 

// 코드를 작성 하는 순서에 따라 두 가지 경우가 나타남. 

1) fillStyle 먼저하면 파란색이 빨간색을 덮고

2) strokeRect 먼저 하면 빨간색이 파란색을 덮음

 

 

 

 

<globalAlpha 속성>

 

ctx.lineWidth = 15;

ctx.fillStyle = "red";

ctx.strokeStyle ="blue";

ctx.beginPath();

ctx.rect(50, 50, 100, 100);

ctx.globalAlpha = ???; // 색상의 투명도를 보겠다. (0.0~1.0까지)

ctx.fill();

ctx.stroke();

 

 

 

1-4) 그라데이션 스타일

  • 두 가지 이상의 색상이 점진적으로 변하는 효과
  • createLinearGradiant(x1,y1,x2,y2) - 선형 그라데이션 지정(x1, y1 시작점, x2, y2 종료점) ; 직선형으로 색깔 변함
  • createRadialGradiant(x1,y1,r1,x2,y2,r2) - 방사형 그라데이션 지정 ; 2개의 가상의 원 / 360도 모든 방향으로 색상 변해감
  • addColorStop(오프셋, 색상)  - 그라데이션 경계색 지정(어떤색으로) , 오프셋(어느 위치에서) -> 경계색 위치(시작점 0.0 ~ 끝점 1.0)

 

  • 지정 형식

ctx.beginPath();

var 변수 = ctx.createLinearGradiant(x1,y1, x2,y2);

               ctx.createRadialGradiant(x1,y1,r1,x2,y2,r2);

변수.addColorStop(시작점_오프셋, 색상); // 시작점 0.0

변수.addColorStop(중간점_오프셋, 색상); // 색상 여러개 쓰고 싶음 여러개 넣기 , 중간점 0.x

변수.addColorStop(끝점_오프셋, 색상); // 끝점 1.0

 

ctx.fillStyle = 변수; 

 

 

1-4-1) 선형 그라데이션

 

var gradiant = ctx.createLinearGradiant(0,0,150,150); // 사각형 그려서 빨,노,파 선형 그라데이션으로 채우고 싶다. 

gradiant.addColorStop(0,0,'red');

gradiant.addColorStop(0.5,'yellow');

gradiant.addColorStop(1.0, 'blue');

ctx.fillStyle=gradiant; // fillStyle 의 속성에 지정해줌

ctx.fillRect(0,0,150,150);

 

 

 

1) ctx.fillRect(50,0,200,250) // 내가 그라데이션으로 지정하는 영역(0,0,150,150)과 그걸 이용해 채우는 영역이 (50,0,200,250)이라면 약간의 의도와 다르게 채워질 수 있음

2) ctx.fillRect(0,0, canvas.width, canvas.height); 

// 이게 원래 캔바스에 색깔이 채워진 모습 (파란색이 길게 칠해져 있음)

 

 

ctx.createLinearGradiant(x,y,x,y);

// 시작점, 종료점을 어떻게 주느냐에 따라, 그 색깔이 변화하는 그라데이션의 진행방향이 달라진다. 

 

 

 

 

 

1-4-2) 방사형 그라데이션

 

 

var gradiant = ctx.createRadialGradiant(150,150,30, 150,150,130);

gradiant.addColorStop(0.0, 'red');

gradiant.addColorStop(0.5, 'yellow');

gradiant.addColorStop(1.0, 'blue');

ctx.fillStyle = gradiant;

 

ctx.fillRect(0,0, canvas.width, canvas.height); // 왼쪽 첫번째 그림

 

ctx.arc(150,150,150, 0, 2*Math.PI, false);

ctx.fill() // 왼쪽 두번째 그림

 

 

1-4-3) 방사형 그라데이션

- 중심의 좌표와 반지름에 따른 그라데이션 효과의 변화

var gradiant = ctx.createRadialGradiant(x1,y1,r1,x2,y2,r2);

gradiant.addColorStop(0.0,'yellow');

gradiant.addColorStop(1.0, 'blue');

ctx.fillStyle = gradiant;

ctx.fillRect(,0, canvas.width, canvas.height);

 

 

// 중심의 좌표와 반지름 달리 줌으로서, 다른 효과를 얻을 수 있다. 

 

 

 

첫번째 원 / 두번째 원

 

 

 

1-5) 패턴 스타일 => 이미지 이용하여 패턴 만든 다음, 그걸 사용해 채우기함

 

  • createPattern(이미지변수, 반복형식)

- 채우기를 위한 이미지 패턴 생성

var  변수1 = new Image();

변수1.src = '이미지 파일 주소';

var 변수2 = ctx.createPattern(변수1, 반복형식);

ctx.fillStyle = 변수 2;

 

-반복형식의 값

-x축, y축 모두 반복한다.

 

 

 

 

var img = new image();

img.src = "smile.jpg";

img.onLoad = function(){ // img 가 로드되었을 때(이벤트)

ctx.beginPath();

var pattern = ctx.createPattern(img, "repaeat");

ctx.fillStyle = pattern; // 원 내부 채우는 스타일(패턴)

ctx.arc(100,100,70,0,2*Math.PI, false);

ctx.fill(); // 원 채우기

ctx.strokeStyle = pattern; // 사각형 테두리 채우기

ctx.lineWidth = 25;

ctx.strokeRect(10,10,180,180); // 사각형도 그리고 이미지 가져올때 (도중에) 시간이 오래 걸리면, 패턴 만들면 내가 원하는 패턴이 안만들어 질지도

}

=> img.onload

- (이벤트) 가져오는 도중, 패턴 만들 이미지가 다운로드 될때 까지 기다렸다가 패턴 만들어라.  

 

1-6) 그림자 스타일

 

  • 관련속성
  • shadowColor - 그림자 색상 지정(기본값: 완전 투명한 검은색 rgba(0,0,0,0) )
  • shadowOffsetX - 대상을 기준으로 그림자의 수평(x축) 오프셋 지정(기본값: 0 )
  • shadowOffsetY- 대상을 기준으로 그림자의 수직(y축) 오프셋 지정(기본값: 0)
  • shadowBlur - 그림자의 흐림정도 지정(기본값: 0)

(예제1)

ctx.shadowOffsetX = 10;

ctx.shadowOffsetY = 10;

ctx.shadowColor ='green';

ctx.shadowBlur = 1; // 거의 없는 

ctx.fillStyle ='rgba(220,11,93,0.8(투명))';

ctx.fillRect(120,120,100,100); // 사각형 그림

 

 

 

(예제2)

ctx.fillStyle = 'rgba(255,0,0,1.0)'; // 얘는 한번만 스탈 지정 해주네....빨간색으로 

ctx.shadowOffsetX = -5;

ctx.shadowOffsetY = -10;

ctx.shadowColor = 'black';

ctx.shadowBlur = 5;

ctx.fillRect(50,50,100,250);

------------------------------

 

ctx.shadowOffsetX= 10;

ctx.shadowOffsetY = 40;

ctx.shadowColor = 'black';

ctx.shadowBlur = 10;

ctx.fillRect(250,50,100,250);

-------------------------------

ctx.shadowOffsetX =40;

ctx.shadowOffsetY = 10;

ctx.shadowColor = 'black';

ctx.shadowBlur =30;

ctx.fillRect(450,50,100,250);

 

 

1-7) 도형 합성

 

- 도형이 그려지는 순서에 상관 없이 도형 간의 겹쳐지는 부분에 대한 다양한 처리가 가능( 기본은 나중이 앞 겹침)

- 속성:

- source-atop, source-in, source-out, source-over (기본값) => 속성 지정 이후에 그려진 도형

- destination-atop, destination-in, destination-out, destination-over => 속성 지정 이전에 먼저 그려진 도형

( 먼저 그려진 도형 관점)

- lighter, copy, xor

 

ctx.beginPath();

ctx.fillStyle = 'green';

ctx.arc(75,100,60,0,2*Math.PI, true);

ctx.fill();

ctx.globalCompositeOperation = "속성값";

ctx.beginPath();

ctx.fillStyle = 'red';

ctx.arc(125,100,60,0, 2*Math*PI*, true);

ctx.fill();

> 실제 점선은 없음

 

 

 

 

 

 

 

 

 

 

 

 

 

2) 텍스트 그리기(어떻게 그려 넣을 거냐)

- 관련 메서드

  • strokeText(텍스트, x, y, [maxWidth])

- 지정된 위치 (x, y)를 기준으로 테두리만 있는 텍스트를 그림

- maxWidth -> 텍스트가 maxWidth의 크기에 맞춰 조정되어 그려짐

 

  • fillText(텍스트, x, y, [maxWidth])

- 지정된 위치 (x, y)를 기준으로 색이 채워진 텍스트를 그림

 

  • 변수 <- measureText(텍스트)

- 현재 글꼴에서 주어진 텍스트의 폭을 반환

- 변수.width

 

<텍스트 그리기>

 

예제1)

 

ctx.font = "italic 40pt 궁서체";

ctx.strokeStyle = "red";

ctx.lineWidth = 2;

ctx.strokeText("컴퓨터 과학 HTML5" , 20, 65);

 

gradiant = ctx.createLinearGradiant(0, 0, 600, 0); // x축으로 색상이 변함

gradiant.addColorStop("0.0", "magenta");

gradiant.addColorStop("0.25", "blue");

gradiant.addColorStop("0.50", "green");

gradiant.addColorStop("0.75", "yellow");

gradiant.addColorStop("1.0", "red");

ctx.fillStyle = gradiant;

ctx.fillText("컴퓨터과학 HTML5", 20, 150); // 글자 테두리(red) 까지 바뀜 

ctx.font = "35pt 휴면옛체";

ctx.lineWidth = 10;

ctx.fillStyle = 'cyan';

ctx.strokeText("컴퓨터과학 HTML5", 20, 220);

ctx.fillText("컴퓨터과학 HTML5", 20, 220); // strokeStyle 은 여전히 red 이고, 텍스트 내부 색만 채워서 테두리 빨강, 글자 내부는 cyan 색이다.

 

<관련속성>

 

- font :

- 글자 스타일, 글자크기, 글자체 지정(기본값: "10px sans-serif")

- ctx.font = "italic 15pt 굴림체"

 

-textAlign : 문자진행 방향에 따라

- 수평방향(x 축)의 정렬 방식 지정 -> left, right, center,start(기본값), end

 

- textBaseline: 

- 텍스트의 수직방향(y 축)의 기준선지정

- top, hanging, middle, alphabetic, ideobetic(기본값), ideographic, bottom

 

left - 텍스트의 시작이 y축 바짝 붙어서 시작,

right - 텍스트의 끝이  y축 바짝 붙어서 시작,

center - 텍스트가 주어진 x, y축 점에 텍스트의 중간이 옴

 

 

 

 

 

 

 

 

 

 

 

예제2)

 

ctx.font = "40pt 궁서체";

ctx.strokeText("HTML5캔버스", 60,70);

 

ctx.textAlign = 'left';

ctx.textBaseline = 'top';

ctx.fillStyle = "blue";

ctx.fillText("HTML5 캔버스", 60, 70);

 

ctx.font ="45pt arial";

ctx.textAlign = 'right';

ctx.textBaseline = 'middle';

ctx.strokeStyle ="red";

ctx.strokeText("HTML5 캔버스", 430, 140);

 

 

 

 

'방송대_HTML5' 카테고리의 다른 글

HTML5_8강 SVG(Scalable Vector Graphic)  (0) 2021.10.06
HTML5_7강) 캔버스(3)  (0) 2021.09.27
HTML5_5강) 캔버스(1)  (0) 2021.09.18