[英]Canvas - Animating rotated text
What do I need to do to this animation to make the text animate along with the background image? 我需要对此动画做些什么以使文本与背景图像一起动画?
I have seen a couple of different examples online but either they don't have the text rotated like I do (which is causing the problem) or they don't explain the maths behind the solution. 我在网上看到了几个不同的示例,但是它们要么没有像我一样旋转文本(这导致了问题),要么它们没有解释解决方案背后的数学原理。
This is quite good - http://tech.pro/tutorial/1008/creating-a-roulette-wheel-using-html5-canvas but it doesn't offer a great insight into the use of any of the Math functions. 这非常好-http://tech.pro/tutorial/1008/creating-a-roulette-wheel-using-html5-canvas,但是它不能很好地理解任何Math函数的使用。
I obviously need to affect the line: 我显然需要影响这一行:
context.rotate(i * arc);
in the loop that writes the text but I am unsure of the maths involved. 在编写文本的循环中,但是我不确定所涉及的数学。
var cvs = document.getElementById("cvs");
var context = cvs.getContext("2d");
var height = 400,
width = 400,
spinning = false,
angle = 0,
awards = [100,200,300,400,500,600,700,800,900,1000,1100,1200],
segmentCount = 12,
angleAmount = 30,
arc = Math.PI / 6,
image = new Image();
image.src = 'http://placehold.it/400x400';
function draw() {
// clear
context.clearRect(0,0,width,height);
// rotate whole wheel here?
context.save();
context.translate(height/2, width/2);
context.rotate(angle * (Math.PI / 180));
context.drawImage(image,-width/2,-height/2);
context.restore();
// draw the prize amount text
for(var i = 0; i < segmentCount; i++){
context.save();
context.translate(height/2, width/2);
context.font = "bold 18px sans-serif";
context.textAlign = "end";
context.rotate(i * arc);
context.fillStyle = "#000000";
context.textBaseline = 'middle';
context.fillText(awards[i],145,0);
context.restore();
angle += angleAmount;
}
}
function update(){
draw();
angle += 5;
setTimeout(update,1000/30);
}
image.onload = update;
I think you got confused by the way you are using the 'angle' var : it is in fact the var that holds the current rotation, and you also use it in the for loop that draws the amounts (angle+=angleAmount)... just to increase it. 我认为您对使用'angle'var的方式感到困惑:实际上,它是保持当前旋转的var,并且还可以在for循环中使用它来绘制数量(angle + = angleAmount)...只是为了增加它。 Luckily enough you add 360° to it so it did not create a bug.
幸运的是,您向其中添加了360°,因此它不会产生错误。
So first thing is to stop increasing this var in the text drawing for loop, second thing is to add the current rotation angle to each text draw (with a degree-> rad conversion) : 因此,第一件事是在循环的文本绘图中停止增加此变量,第二件事是将当前旋转角度添加到每个文本绘图中(使用度->弧度转换):
context.rotate(( i * angleAmount + angle ) * (Math.PI / 180));
http://jsfiddle.net/gamealchemist/fwter56k/4/ http://jsfiddle.net/gamealchemist/fwter56k/4/
(or with a bit of optimisation : http://jsfiddle.net/gamealchemist/fwter56k/5/ ) (或进行一些优化: http : //jsfiddle.net/gamealchemist/fwter56k/5/ )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.