CSS&JS/⚡Thinkers

<canvas>로 피자 조각(파이) 그리기 - 삼각함수 사용

arancia_ 2021. 4. 3. 15:27

지난 게시물 참조 : 시작점과 반지름과 각도만 주어진 상황에서 끝점 x,y좌표를 삼각함수를 이용하여 찾는 방법

aosceno.tistory.com/511

 
sin, cos로 각도와 대각선 길이만 가지고 x,y좌표 찍기

HTML,CSS 1 2 3 4 5 6 7 8 9 10 11 *{margin:0;padding:0;box-sizing:border-box;} #myDiv{position:relative;width:100%;height:100vh;} #myCanvas{width:100%;height:100%;background:#ccc;}     이 브라우..

aosceno.tistory.com

 

 

HTML과 CSS

JS

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
const container = document.getElementById('container');
const cv = document.getElementsByTagName('canvas')[0];
const ctx = cv.getContext('2d');
 
/* 01. 캔버스 크기 설정 */
function setSize(){
    cv.width = container.clientWidth;
    cv.height = container.clientHeight;
    //0)clear
    ctx.clearRect(0,0,container.clientWidth,container.clientHeight);
    draw(getRad(0), getRad(330), 450300'red'true);
    draw(getRad(180), getRad(210), 150300'red'false);
 
    draw(getRad(0), getRad(30), 450300'orange'false);
    draw(getRad(180), getRad(150), 150300'orange'true);
 
    draw(getRad(270), getRad(240), 300150'yellow'true);
    draw(getRad(90), getRad(120), 300450'yellow'false);
 
    draw(getRad(90), getRad(60), 300450'green'true);
    draw(getRad(270), getRad(300), 300150'green'false);
 
    draw(getRad(330), getRad(300), 
        300 + 150 * Math.cos(getRad(30)), 
        300 + 150 * Math.sin(getRad(-30)), 'skyblue'true);
    draw(getRad(30), getRad(60), 
        300 + 150 * Math.cos(getRad(30)), 
        300 + 150 * Math.sin(getRad(30)), 'skyblue'false);
 
    draw(getRad(210), getRad(240), 
        300 - 150 * Math.cos(getRad(30)), 
        300 - 150 * Math.sin(getRad(30)), 'salmon'false);
    draw(getRad(150), getRad(120), 
        300 - 150 * Math.cos(getRad(-30)), 
        300 - 150 * Math.sin(getRad(-30)), 'salmon'true);
    
}//setSize()
 
/* 02. 그리기 메쏘드 */
function getRad(deg){ return deg * (Math.PI / 180);}
 
// 300,300 위치에서, 반지름150의, 30도 짜리 피자 조각을 그려보자
function draw(start_deg, end_deg, endX, endY, fColor, bl){
    //1)arc 그리기
    ctx.lineWidth = 10;
    ctx.beginPath();
    ctx.arc(300,300150, start_deg, end_deg, bl);
    ctx.stroke();
    //2)반지름 그리기
    ctx.lineTo(300,300);
    ctx.stroke();
    ctx.lineTo(endX,endY);
    ctx.stroke();
    ctx.fillStyle = fColor;
    ctx.fill();
    ctx.closePath();
}
 
setSize();
/* 윈도우 크기 변경시 */
window.addEventListener('resize',setSize);
 
cs