2017-04-26 58 views
1

如果我在JavaScript畫布中有以下三角形的基本繪圖,我將如何沿中心旋轉它,例如30度?這與可能的重複有點不同,因爲它不是rect,它是沿原點的一束線。在JS畫布中旋轉ctx的線條

// Rotate 30 degrees when origin is (5,5) 
ctx.beginPath(); 
ctx.moveTo(5,0); 
ctx.lineTo(10,10); 
ctx.lineTo(0,10); 
ctx.lineTo(5,0); 
ctx.stroke(); 

因此,不是看到一個正常的三角形,而是看到一個三角形有點傾斜。

在此先感謝!

+0

的可能的複製[HTML5畫布 - 旋轉對象,而不移動座標(http://stackoverflow.com/questions/17125632/html5-canvas-rotate-object-without-moving-coordinates) – Sphinxxx

回答

1

你可以完成,使用畫布rotate方法

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

 
var deg = 30; 
 

 
ctx.save(); // save canvas 
 

 
ctx.rotate(deg * Math.PI/180); // rotate canvas 
 

 
ctx.beginPath(); 
 
ctx.moveTo(5,0); 
 
ctx.lineTo(10,10); 
 
ctx.lineTo(0,10); 
 
ctx.lineTo(5,0); 
 
ctx.stroke(); 
 

 
ctx.restore(); // restore canvas
<canvas id="canvas" width="218" height="218" style="border:1px solid #d3d3d3"></canvas>

注:確保旋轉之前保存畫布狀態和繪圖後恢復三角形,以便將來的圖紙不會旋轉。

+0

你將不得不添加ctx.translate(5,5),然後這將工作 –

+0

@ AssafiCohen-Arazi無論如何這工作,如果你想改變那麼你需要的位置*翻譯* –

1

最佳選擇是在自己的本地座標系中定義三角形。如果您打算移動它,則需要沿着畫布的原點。但是你不需要改變三角形的位置和旋轉。

因此,將三角形定義爲其自身座標系中的一組點,其中0,0是旋轉中心。

// you had 
/* 
ctx.moveTo(5,0); 
ctx.lineTo(10,10); 
ctx.lineTo(0,10); 
ctx.lineTo(5,0); */ 

// subtracting 5 from x and y to give 
var triangle = [0,-5,5,5,-5,5]; // dont need the last point will use closePath 

從一組點畫出的形狀的功能,使生活變得更輕鬆

function drawShape(shape, close){ 
    var i = 0; 
    ctx.beginPath(); 
    ctx.moveTo(shape[i++], shape[i++]); 
    while(i < shape.length){ 
     ctx.lineTo(shape[i++], shape[i++]); 
    } 
    if(close){ ctx.closePath() } 
    ctx.stroke(); 
} 

現在一個函數來設置的變換

function setPosScaleRotation(x,y,scale,rot){ 
    ctx.setTransform(scale,0,0,scale,x,y); 
    ctx.rotate(rot); 
} 
// and a function to restore the default transform 
function restoreDefaultTransform(){ 
    ctx.setTransform(1,0,0,1,0,0); 
} 

現在很容易得出你想要的形狀

setPosScaleRotation(5,5,1,deg * Math.PI/180); // 30Pi/180 = 3Pi/18 = Pi/6 
drawShape(triangle,true); 

或將轉換並繪製成相同的功能

function drawShape(shape, close, x, y, scale, rot){ 
    var i = 0; 
    ctx.setTransform(scale, 0, 0, scale, x, y); 
    ctx.rotate(rot); 
    ctx.beginPath(); 
    ctx.moveTo(shape[i++], shape[i++]); 
    while(i < shape.length){ 
     ctx.lineTo(shape[i++], shape[i++]); 
    } 
    if(close){ ctx.closePath() } 
    ctx.stroke(); 
} 

然後

drawShape(triangle, true, 5, 5, 1, Math.PI /6); 
drawShape(triangle, true, 100, 100,1, Math.PI + Math.PI/6); // draw at 100,100 at 180 from other triangle