简体   繁体   中英

Canvas - Animating rotated text

What do I need to do to this animation to make the text animate along with the background image?

Fiddle here

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.

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. Luckily enough you add 360° to it so it did not create a bug.
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/

(or with a bit of optimisation : http://jsfiddle.net/gamealchemist/fwter56k/5/ )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM