2017-02-15 3 views
0

저는 400x300 HTML 캔버스를 가지고 있고 원과 7 개의 삼각형을 사용하여 태양을 그려 나가려고합니다. 삼각형을 그릴 때는 this SO Answer에 표시된대로 번역, 회전, 번역을 수행합니다. 그러나 삼각형 중 일부는 동일한 각도를 갖는 것처럼 겹칩니다.중첩없이 중점을 중심으로 삼각형을 회전하십시오.

http://codepen.io/ralrom/pen/bgZYRO

내가 잘못 무엇을 알아낼 수 없습니다, 나는 계산 라디안을 확인하고 0과 2 * PI 사이에 그들은 모두 가을.

var drawSun = function() { 

    // Circle 
    context.beginPath(); 
    context.arc(75, 75, 30, 0, Math.PI * 2, true); 
    context.closePath(); 
    context.fill(); 

    context.save(); 

    // Triangles 
    for (var i = 0; i < 7; i++) { 

     // Rotate the canvas around a point 
     angle = i * 360/7; 
     console.log(angle, angle * Math.PI/180); 
     context.translate(75, 75); 
     context.rotate(angle * Math.PI/180); 
     context.translate(-75, -75); 

     // Draw the triangle 
     context.beginPath(); 
     context.fillStyle = 'rgba(0,0,0,0.5)'; 
     context.moveTo(60, 35); 
     context.lineTo(75, 15); 
     context.lineTo(90, 35); 
     context.closePath(); 
     context.fill(); 

     context.restore(); 
    } 
} 

답변

2

때로는 여기에 답이 많은 점이 있지만 실제로 좋지 않습니다. ctx.setTransform을 사용하면 기존 변환을 완전히 대체하므로 변환을 처리하는 것이 훨씬 쉬워집니다. 따라서 당신이 어디에 있는지 알기 위해 국가를 구할 필요가 없습니다.

또한 객체를 렌더링 할 때 항상 자신의 좌표를 회전 중심으로 배치 할 때 도움이됩니다. 그 센터를 필요한 곳에 옮깁니다.

어쨌든 다음과 같이 할 수 있습니다. 이 함수는 다른 포인트 수를 처리하며 불필요한 가까운 경로, 복원 저장 및 Deg에서 라디안으로의 변환없이 좀 더 체계적으로 구성됩니다.

var ctx = canvas.getContext('2d'); 
 

 
var drawSun = function(x,y,rad,count) { 
 
    var drawRay = function(ang){ 
 
    // Half width, note I get width from 2PI*r but as I need half I drop the 2 
 
    var width = (Math.PI * (rad + 5))/count; 
 
    ctx.setTransform(1,0,0,1,x,y); 
 
    ctx.rotate(ang); 
 
    ctx.beginPath(); 
 
    ctx.moveTo(-width, rad + 5); 
 
    ctx.lineTo(0, rad + 20); 
 
    ctx.lineTo(width, rad + 5); 
 
    ctx.fill(); 
 
    } 
 
    ctx.fillStyle = "#F90"; 
 
    ctx.setTransform(1,0,0,1,x,y); // move sun center to where it should be. 
 
    ctx.beginPath(); 
 
    ctx.arc(0, 0, rad, 0, Math.PI * 2, true); // draw sun at 0,0 
 
    ctx.fill(); 
 

 
    for (var i = 0; i < count; i++) { 
 
    drawRay((i/count) * Math.PI * 2); 
 
    // if you want to draw with first ray top center 
 
    // you need to offset by half a step 
 
    //drawRay(((i/count)-(count/2)) * Math.PI * 2); 
 
    } 
 
    // done and if you want you can reset to the default transform with 
 
    // ctx.setTransform(1,0,0,1,0,0); 
 
} 
 
drawSun(100,100,30,7);
<canvas id="canvas" width=200 height=200></canvas>

관련 문제