2017-06-15 44 views
1

我打算圍繞其中心在畫布上旋轉圖表,同時保持字母直立。我正在嘗試使用ctx.rotate(#),但它使用以畫布左側爲中心旋轉整個圖表。如何在保持數字直立的同時在畫布上旋轉圖表?

下面的鏈接提供了一個視覺效果:我希望它看起來像綠色,而不是紅色,就像它現在與我的代碼一樣。 Visual Explanation

以下是的jsfiddle:http://jsfiddle.net/ddxarcag/143/

我的代碼如下:

<script> 
$(document).ready(function() { 
    init(); 

function init() { 
    var canvas = document.getElementById("canvas"); 
    var ctx = canvas.getContext("2d"); 
    draw(ctx); 
} 

function draw(ctx) { 
    // layer1/Line 
    ctx.rotate(00); 
    ctx.beginPath(); 
    ctx.moveTo(75.1, 7.7); 
    ctx.lineTo(162.9, 7.7); 
    ctx.stroke(); 
    function WordSelector1() { 
    var word = ['A', 'B', 'C']; 
    var random = word[Math.floor(Math.random() * word.length)]; 
    return random; 
} 
    var x = WordSelector1(); 
    // layer1/P 
    ctx.font = "12.0px 'Myriad Pro'"; 
    ctx.rotate(0); 
    ctx.fillText(x, 60.0, 10.0); 
} 
}); 
</script> 

任何幫助將非常感激。謝謝!

回答

0

一旦您知道如何將原點(0,0)移動到另一個點,然後圍繞它旋轉軸,則在畫布中繪製旋轉的圖形會比較容易。

我在代碼中添加了一些註釋,因爲不重複代碼和解釋。

我還將功能從$(document).ready中移出,並更改了一些數字以獲取更多四捨五入的值。

$(document).ready(function() { 
 
    init(); 
 
}); 
 

 
function init() { 
 
    var canvas = document.getElementById("canvas"); 
 
    var ctx = canvas.getContext("2d"); 
 
    draw(ctx); 
 
} 
 

 
function draw(ctx) { 
 
    ctx.font = "12.0px 'Myriad Pro'"; 
 
    var angle = Math.random()*150; //Run more times to see other angles 
 
    
 
    //This translates the 0,0 to the center of the horizontal line 
 
    ctx.translate(100, 100); 
 
    
 
    //This draws the original straight line 
 
    ctx.beginPath(); 
 
    ctx.moveTo(-50, 0); //The coordinates are relative to the new origin 
 
    ctx.lineTo(50, 0); 
 
    ctx.stroke(); 
 
    //Draw the first letter 
 
    var x = WordSelector1(); 
 
    ctx.fillText(x, -60, 0); 
 

 
    //This section draws the rotated line with the text straight 
 

 
    //Rotate the canvas axes by "angle" 
 
    ctx.rotate(angle * Math.PI/180); 
 
    ctx.beginPath(); 
 
    ctx.moveTo(-50, 0); //The relative coordinates DO NOT change 
 
    ctx.lineTo(50, 0); //This shows that the axes rotate, not the drawing 
 
    ctx.stroke(); 
 

 
    var x = WordSelector1(); 
 
    ctx.translate(-60,0); //The origin must now move where the letter is to be placed 
 
    ctx.rotate(-angle * Math.PI/180); //Counter-rotate by "-angle" 
 
    ctx.fillText(x, 0, 0); //Draw the letter 
 
} 
 

 
function WordSelector1() { 
 
    var word = ['A', 'B', 'C']; 
 
    var random = word[Math.floor(Math.random() * word.length)]; 
 
    return random; 
 
}
canvas{ 
 
    border: 1px solid; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<canvas id="canvas" width="200" height="200"></canvas>

一個警告:一切都畫後,因爲它是由-angle旋轉軸平行結束在畫布上的邊界,但產地是哪裏的最後一個字母被放置。您可能想要使用ctx.save()ctx.restore()以避免必須恢復翻譯和旋轉。

+0

這非常有幫助!精美的作品。感謝您花時間在代碼中加入評論,因爲我試圖實際學習這些內容,而不僅僅是讓它發揮作用。謝謝! – Snoops