【问题标题】:Canvas - Animating rotated textCanvas - 动画旋转文本
【发布时间】:2015-02-18 12:29:30
【问题描述】:

我需要对这个动画做些什么才能使文本与背景图像一起动画?

Fiddle here

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

这很好 - 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;

【问题讨论】:

标签: javascript html animation canvas


【解决方案1】:

我认为您对使用 'angle' var 的方式感到困惑:事实上,它是保存当前旋转的 var,并且您在绘制的 for 循环中使用它数量(角度+=角度数量)......只是为了增加它。幸运的是,您为其添加了 360°,因此它没有产生错误。
所以第一件事是停止在文本绘图中增加这个 var for 循环,第二件事是将当前旋转角度添加到每个文本绘图(使用度数->弧度转换):

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

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

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

【讨论】:

    猜你喜欢
    • 2013-04-06
    • 2012-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多