如何在保持数字直立的同时在画布上旋转图表?

问题描述:

我打算围绕其中心在画布上旋转图表,同时保持字母直立。我正在尝试使用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)移动到另一个点,然后围绕它旋转轴,则在画布中绘制旋转的图形会比较容易。

我在代码中添加了一些注释,因为不重复代码和解释。

我还将功能从$(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