我需要对此动画做些什么以使文本和背景图像一起动画?
Fiddle here
我在网上看到了几个不同的示例,但是它们要么没有像我一样旋转文本(这导致了问题),要么它们没有解释解决方案背后的数学原理。
这非常好-http://tech.pro/tutorial/1008/creating-a-roulette-wheel-using-html5-canvas
但是它不能很好地了解任何Math函数的用法。
我显然需要影响这一行:
context.rotate(i * arc);
在编写文本的循环中,但是我不确定所涉及的数学。
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;
最佳答案
我认为您对使用'angle'var的方式感到困惑:实际上,它是保持当前旋转的var,并且还在for循环中使用它来绘制量(angle + = angleAmount)...只是为了增加它。幸运的是,您向其中添加了360°,因此它不会产生错误。
因此,第一件事是停止在循环的文本绘图中增加此var,第二件事是将当前旋转角度添加到每个文本绘图中(使用度->弧度转换):
context.rotate(( i * angleAmount + angle ) * (Math.PI / 180));
http://jsfiddle.net/gamealchemist/fwter56k/4/
(或稍加优化:http://jsfiddle.net/gamealchemist/fwter56k/5/)
关于javascript - Canvas -动画旋转文本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27568267/