CSS&JS/⚡Thinkers
<canvas> sin, cos로 각도와 대각선 길이만 가지고 x,y좌표 찍기
arancia_
2021. 4. 2. 10:28
HTML,CSS
1 2 3 4 5 6 7 8 9 10 11 | <style> *{margin:0;padding:0;box-sizing:border-box;} #myDiv{position:relative;width:100%;height:100vh;} #myCanvas{width:100%;height:100%;background:#ccc;} </style> </head> <body> <div id="myDiv"> <canvas id="myCanvas">이 브라우저는 캔버스를 지원하지 않습니다</canvas> </div><!-- myDiv --> | cs |
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 63 64 | const myDiv = document.getElementById('myDiv'); const myCanvas = document.getElementById('myCanvas'); const ctx = myCanvas.getContext('2d'); myCanvas.width = window.innerWidth; myCanvas.height = window.innerHeight; ctx.font = '24px Dotum' /* Q1 : 내가 (300,300)에서 30도 100만큼 길이의 대각선을 그리고 싶다 */ ctx.beginPath(); ctx.moveTo(300,300); ctx.lineTo(300 + useSinCos('c',30,100), 300 + useSinCos('s',30,100)); ctx.stroke(); ctx.closePath(); ctx.fillRect(295,295,10,10); ctx.fillText('1번',400,380) /* Q2 : 내가 (300,300)의 위치에서 오른쪽 위로 30도 만큼의 대각선을 그리고 싶다 */ ctx.fillStyle = 'red'; ctx.strokeStyle = 'red'; ctx.beginPath(); ctx.moveTo(300,300); ctx.lineTo(300 + (useSinCos('c',30,100)), 300 - useSinCos('s',30,100)); ctx.stroke(); ctx.closePath(); ctx.fillText('2번',400,250) /* Q3 : 내가 (300,300)의 위치에서 왼쪽 위로 30도 만큼의 대각선을 그리고 싶다 */ ctx.fillStyle = 'blue'; ctx.strokeStyle = 'blue'; ctx.beginPath(); ctx.moveTo(300,300); ctx.lineTo(300 - (useSinCos('c',30,100)), 300 - useSinCos('s',30,100)); ctx.stroke(); ctx.closePath(); ctx.fillText('3번',170,250) /* Q4 : 내가 (300,300)의 위치에서 왼쪽 아래로 30도 만큼의 대각선을 그리고 싶다 */ ctx.fillStyle = '#ffcd01'; ctx.strokeStyle = '#ffcd01'; ctx.beginPath(); ctx.moveTo(300,300); ctx.lineTo(300 - (useSinCos('c',30,100)), 300 + useSinCos('s',30,100)); ctx.stroke(); ctx.closePath(); ctx.fillText('4번',170,380) function useSinCos(type, deg, rad){ deg = deg * Math.PI / 180; // 180도 = 1π //1도 = π / 180 //n도 = n * (π/180) switch(type){ case 's': return rad * Math.sin(deg); break; case 'c': return rad * Math.cos(deg); break; }//switch }//useSinCos | cs |