使用javascript在画布中旋转文本 [英] Rotate text in a canvas with javascript
问题描述
在下面的代码中,我想在javascript中旋转数组中每个元素的文本。如果我使用例如 ctx.rotate(Math.PI / 10)
之前的filltext,它旋转所有的元素。文本的位置也会随着 ctx.rotate(Math.PI / 10)
改变,如果我使用90度, ctx.rotate(Math。 PI / 2)
文本不会显示在画布上。
In the following code i want to rotate the text of each element of the array in javascript. If i use for example ctx.rotate(Math.PI/10)
before the filltext, it rotates all the elements. The positioning of the text also changes with ctx.rotate(Math.PI/10)
and if i use 90 degrees, ctx.rotate(Math.PI/2)
the text does not show on the canvas.
<html>
<canvas id="myCanvas" width="300" height="300" style="border:1px solid #d3d3d3;"></canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var x = new Array("Day1","Day2","Day3","Day4","Day5");
ctx.rotate(Math.PI/10);
for(var i = 0; i < x.length; i++){
ctx.fillText(x[i],i*50+20,50);
}
</script>
</html>
正如我所说,我想要旋转每个元素自己,应该保持与非旋转文本相同,如上面的代码。因此,每个元件必须绕其自身的轴旋转。
As i said, i want to rotate each element on its own and with that the positioning of each element should stay the same as in the non-rotated text as in the code above. Thus each element has to rotate around its own axis. How can i achieve this?
推荐答案
在代码中做了一些修改,它应该有助于:
Have made some changes in your code, it should help:
<html>
<canvas id="myCanvas" width="300" height="300" style="border:1px solid
#d3d3d3;"></canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var x = new Array("Day1","Day2","Day3","Day4","Day5");
for(var i = 0; i < x.length; i++){
var size = ctx.measureText(x[i]);
ctx.save();
var tx = (i*50+20) + (size.width/2);
var ty = (50);
ctx.translate(tx,ty);
ctx.rotate(Math.PI / 10);
ctx.translate(-tx,-ty);
ctx.fillText(x[i],i*50+20,50);
ctx.restore();
}
</script>
</html>
这篇关于使用javascript在画布中旋转文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!