2017-02-15 11 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>

関連する問題