画布 - 为旋转文本添加动画效果

Canvas - Animating rotated text

本文关键字:动画 添加 文本 旋转 画布      更新时间:2023-09-26

我需要对此动画执行什么操作才能使文本与背景图像一起动画化?

在这里摆弄

在网上看到了几个不同的例子,但他们要么不像我那样旋转文本(这导致了问题(,要么他们没有解释解决方案背后的数学。

这很好 - http://tech.pro/tutorial/1008/creating-a-roulette-wheel-using-html5-canvas但它没有提供对任何数学函数使用的深刻见解。

我显然需要影响这条线:

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;

我想你对使用"角度"var 的方式感到困惑:它实际上是保存当前旋转的 var,你也在绘制数量的 for 循环中使用它(角度+=angleAmount(...只是为了增加它。幸运的是,您为其添加了360°,因此它不会产生错误。
所以第一件事是停止在循环的文本绘制中增加这个变量,第二件事是将当前旋转角度添加到每个文本绘制中(使用度> rad 转换(:

   context.rotate(( i * angleAmount + angle ) * (Math.PI / 180));

http://jsfiddle.net/gamealchemist/fwter56k/4/

(或稍作优化:http://jsfiddle.net/gamealchemist/fwter56k/5/(