2013-10-12 3 views
0

Я пытаюсь использовать this «moveTo (x, y)» (по markE) функция для нескольких объектов. This - это то, что я пробовал. И это то, что я пытался сделать:Перемещение нескольких объектов в холсте на координаты x, y

Расчет и перемещение объекта в woriking пример выглядеть следующим образом:

pct += .01; 
// if we're not done, request another animation frame 
if (pct < 1.00) { 
    requestAnimFrame(animate); 
} 

// Calculate the next XY position 
var nextX = startingX + dx * pct; 
var nextY = startingY + dy * pct; 

// Draw the shape 
ctx.clearRect(0, 0, canvas.width, canvas.height); 
ctx.fillRect(nextX, nextY, 40, 30); 

И это то, что я пытаюсь сделать для нескольких форм:

var shapesLength = shapes.length; 
for (var i = 0; i < shapesLength; i++) {// Loop through every object 

var tmpShape = shapes[i];//selecting shape 

    tmpShape.pct += .01;// increment pct towards 100% 

    // if we're not done, request another animation frame 
    if (tmpShape.pct < 1.00) { 
     requestAnimFrame(animate); 
    } 

    // Calculate the next XY position 
    var nextX = tmpShape.startingX + tmpShape.dx * tmpShape.pct; 
     var nextY = tmpShape.startingY + tmpShape.dy * tmpShape.pct; 

    // Draw the shape 
    ctx.clearRect(0, 0, canvas.width, canvas.height); 
    ctx.fillRect(nextX, nextY, 10, 10); 
}; 

Но что-то пошло не так, и я не знаю, что.

ответ

1

Неправильно то, что requestAnimFrame находится внутри вашей петли.

Вы хотите вызвать requestAnimFrame один раз за пределами своего цикла.

Вот пример кода и Fiddle: http://jsfiddle.net/m1erickson/HAbfm/

<!doctype html> 
<html> 
<head> 
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> 
<script src="http://code.jquery.com/jquery.min.js"></script> 

<style> 
    body{ background-color: ivory; } 
    canvas{border:1px solid red;} 
</style> 

<script> 
    $(function(){ 

     var canvas=document.getElementById("canvas"); 
     var ctx=canvas.getContext("2d"); 

     window.requestAnimFrame = (function(callback) { 
      return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || 
      function(callback) { 
      window.setTimeout(callback, 1000/60); 
      }; 
     })(); 

     var shapes=[]; 
     shapes.push({startX:10, startY:10, endX:140, endY:140, color:"red"}); 
     shapes.push({startX:280, startY:10, endX:150, endY:140, color:"green"}); 
     shapes.push({startX:10, startY:280, endX:140, endY:150, color:"blue"}); 
     shapes.push({startX:280, startY:280, endX:150, endY:150, color:"gold"}); 

     var pct=0.00; 
     var fps = 60; 

     animate(); 

     function animate() { 
      setTimeout(function() { 


       // increment the percent (from 0.00 to 1.00) 
       pct+=.01; 

       // clear the canvas 
       ctx.clearRect(0,0,canvas.width,canvas.height); 

       // draw all shapes 
       for(var i=0;i<shapes.length;i++){ 

        // get reference to next shape 
        var shape=shapes[i]; 

        // note: dx/dy are fixed values 
        // they could be put in the shape object for efficiency 
        var dx=shape.endX-shape.startX; 
        var dy=shape.endY-shape.startY; 
        var nextX = shape.startX + dx * pct; 
        var nextY = shape.startY + dy * pct;     
        var shape=shapes[i]; 
        ctx.fillStyle=shape.color; 
        ctx.fillRect(nextX,nextY,7,7); 
       } 

       if(pct<1.00){requestAnimFrame(animate)}; 


      }, 1000/fps); 
     } 


    }); // end $(function(){}); 
</script> 

</head> 

<body> 
    <canvas id="canvas" width=350 height=350></canvas> 
</body> 
</html> 

Вот пример того, как реализовать несколько точек для каждой формы:

http://jsfiddle.net/m1erickson/UNjdC/

[Дополнение: объяснить, как создать формы и анимировать их]

Вы создаете и анимированные формы в 3 этапа:

  1. Создайте полилинию для одной фигуры, которая будет использоваться во время анимации.

  2. Нажмите новую форму в массив фигур []. Каждый объект формы определяет свою собственную полилинию ширины, высоты, цвета и анимации из # 1 выше.

  3. После того, как все новые фигуры находятся в массиве shape [], вызовите animimate(), чтобы анимировать все фигуры вдоль их собственных полипатов.

Вот кодовые биты для шагов 1-3 выше:

// 1. create a polyline for one shape to follow 

points = pointsToSingleArray([ 
    {x:48,y:2}, 
    {x:48,y:365} 
]); 


// 2. push the shape into the shapes array 
// 
// a shape object contains width/height/color and the polyline 

shapes.push({ 
    width: shapeWidth, 
    height: shapeHeight, 
    waypoints: points, 
    color: "red" 
}); 

// 3. After you've pushed all desired shapes into the 
// shapes[] array, call animate() to start draw all 
// objects along their own polyline paths. 

animate(); 
+0

Вот пример того, как реализовать несколько точек для каждой формы: http://jsfiddle.net/m1erickson/UNjdC/ – markE

+0

Как создать мгновенное создание объектов и получить их после достижения точки назначения? – eko24

+0

Массив shape [] содержит определение всех фигур, которые будут нарисованы и анимированы. В этом случае фигурами являются все прямоугольники, у которых есть точки начала и конца анимации и цвета. Если вам нужна мгновенная генерация объектов, просто добавьте новые объекты в массив shape []. Если вы хотите, чтобы объект исчез после достижения точки назначения, удалите эту строку: drawShape (shape, shape.waypoints.length - 1); – markE

Смежные вопросы