最佳選擇是在自己的本地座標系中定義三角形。如果您打算移動它,則需要沿着畫布的原點。但是你不需要改變三角形的位置和旋轉。
因此,將三角形定義爲其自身座標系中的一組點,其中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
的可能的複製[HTML5畫布 - 旋轉對象,而不移動座標(http://stackoverflow.com/questions/17125632/html5-canvas-rotate-object-without-moving-coordinates) – Sphinxxx