2015-09-11 58 views
0

我创建了以下绘制函数:围绕真正的中心旋转三角形?

function draw(ctx, scale, angle) { 
    // DRAW SHAPE: 
    var rotation = (Math.PI/180) * angle; 
    var h = scale * (Math.sqrt(3)/2); 
    var radius = h/4; 
    ctx.fillStyle = '#BE1942'; 
    ctx.strokeStyle = "#FF2159"; 
    ctx.lineJoin = "round"; 
    ctx.lineWidth = radius; 
    ctx.save(); 
    ctx.translate(getCX(), getCY()); 
    ctx.rotate(rotation); 
    ctx.beginPath(); 
    ctx.moveTo(0, -h/2); 
    ctx.lineTo(-scale/2, h/2); 
    ctx.lineTo(scale/2, h/2); 
    ctx.lineTo(0, -h/2); 
    ctx.closePath(); 
    ctx.stroke(); 
    ctx.fill(); 

    // RESET: 
    ctx.restore(); 

    // FINALIZE: 
    ctx.save(); 
} 

我注意到,当我旋转这个三角形,其周围不属实中心旋转,但是在抵消了相当。有一种简单的方法可以使它围绕真正的中心旋转吗?我认为它应该已经做到了,因为我正在从中心坐标绘制它。

+2

您需要翻译旋转之前的旋转中心,然后恢复它,设置一个小提琴 – maioman

回答

1

你的X,Y加起来还不到0,0,但(0,H/2)

ctx.moveTo(0, -h/2); 
ctx.lineTo(-scale/2, h/2); 
ctx.lineTo(scale/2, h/2); 

所以修改你的翻译,或者说

ctx.moveTo(0, -2*h/3); 
ctx.lineTo(-scale/2, h/3); 
ctx.lineTo(scale/2, h/3); 
ctx.lineTo(0, -2*h/3); 
+0

正在制作小提琴的过程中。感谢你的快速回复。像魅力一样工作。 – TastyLemons