2015-04-22 65 views
3

我想在qml畫布中製作一圈線條,但是當我將lineWidth更改爲除1以外的其他東西時,它會弄亂筆畫的位置,以便將它們延伸到中心。QML context2d lineWidth

左:的lineWidth = 1,右:的lineWidth = 2

screenshot

Canvas { 
    id:spinner 
    anchors.centerIn: parent 
    width:400 
    height: 400 
    onPaint: { 
     var ctx = getContext("2d"); 
     var x,y,rotx,roty 
     ctx.reset(); 
     ctx.beginPath(); 

     for (var i=0;i<10;i++){ 
      rotx = Math.cos(Math.PI*2*i/10) 
      roty = Math.sin(Math.PI*2*i/10) 
      x = 10*rotx + this.width/2 
      y = 10*roty + this.height/2 
      ctx.moveTo(x , y) 
      x = (10 + 10)* rotx + this.width/2 
      y = (10 + 10)* roty + this.height/2 
      ctx.lineTo(x , y) 
      ctx.closePath() 
     } 
     ctx.lineWidth = 1; 
     ctx.lineCap = "round"; 
     ctx.stroke(); 
    } 
} 

有人可以幫助我嗎?

回答

1

不應該有任何需要使用closePath()(假設它的工作方式與html5-canvas相同)。所有這些都會告訴畫布將第一點與最後一點連接起來。 moveTo()將創建必要的子路徑。

此外,計算必須被調整到內,外半徑相對於使用中心:

onPaint: { 
    var ctx = getContext("2d"); 
    var x,y,rotx,roty, cx, cy, innerRadius, outerRadius, angle; 
    ctx.reset(); 
    ctx.beginPath(); 

    cx = this.width/2; 
    cy = this.height/2; 
    innerRadius = 10; 
    outerRadius = 100; 

    for (var i=0;i<10;i++){ 
     angle = Math.PI*2*i/10; 
     x = cx + innerRadius * Math.cos(angle); 
     y = cy + innerRadius * Math.sin(angle); 
     ctx.moveTo(x , y) 

     x = cx + outerRadius * Math.cos(angle); 
     y = cy + outerRadius * Math.sin(angle); 
     ctx.lineTo(x , y) 
    } 
    ctx.lineWidth = 1; 
    ctx.lineCap = "round"; 
    ctx.stroke(); 
} 
+0

啊,我明白了。非常感謝! – backpackjoe