0

I'm having trouble trying to make an animation with JavaScript and the HTML5 canvas element.

I need to have an animation that starts in the bottom right corner of my canvas, which moves up diagonally to the top right hand corner and then reverses back the other direction to create a back and forth movement.

I can get my animation to move diagonally, but then I can't get it to change the direction. I'm also having trouble getting the animation to start from the bottom no matter what I do.

The code below currently moves my animation top to bottom diagonally.

var context;
var x = 0;
var y = 0;
var stepx = 1.55;
var stepy = 1.55;

function setupAnimCanvas() {
    var canvas = document.getElementById('assignmenttwoCanvas');
    if (canvas.getContext) {
        ctx = canvas.getContext('2d');
        setInterval('draw();', 20);
        img = new Image();
        img.src = '../images/dragon.png';
        //animation();
    }
}

startPos = (500, 500);
endPos = (0, 0);

function draw() {
    ctx.clearRect(0,0, 500,500);
    drawBackground();
    ctx.drawImage(img, y, x);
    x += 3;
    if(x < endPos){
        x -= stepx;
        y += stepy;
    }
    else if (y > endPos) {
        x += stepx;
        y -= stepy;
    }
    else {
        endPos = startPos;startPos = y;
    }
        moveit();
        setTimeout('mover()',25);
}
4

1 回答 1

0

You can use a delta value for x and y. When the x or y position is at start or end you just reverse the delta by setting delta = -delta;

var dx = -3, dy = -3;

Then simply check for any criteria that would reverse the direction:

if (x < endPos[0] || x > startPos[0] || y < endPos[1] || y > startPos[1] ) {
    dx = -dx;
    dy = -dy;
}

See demo here:
http://jsfiddle.net/AbdiasSoftware/5dSSZ/

The essence of this (see comments and original source lines at fiddler-link)

var startPos = [500, 500];
var endPos = [0, 0];
var dx = -3, dy = -3;
var x = startPos[0], y = startPos[1];

function draw() {
    ctx.clearRect(0, 0, 500, 500);
    ctx.fillRect(x, y, 20, 20); //for demo as no image
    x += dx;
    y += dy;

    if (x < endPos[0] || x > startPos[0] ||
        y < endPos[1] || y > startPos[1] ) {
        dx = -dx;
        dy = -dy;
    }
    setTimeout(draw, 16); //requestAnimationFrame is a better choice
}
于 2013-06-10T08:25:40.613 回答