Показать сообщение отдельно
  #1 (permalink)  
Старый 28.05.2021, 21:26
Кандидат Javascript-наук
Отправить личное сообщение для Katy93 Посмотреть профиль Найти все сообщения от Katy93
 
Регистрация: 28.12.2018
Сообщений: 137

Как сделать, чтобы буквы перемещались после каждой секунды?
Буквы разбросаны по всему канвасу случайным образом (random), мне нужно, чтобы они при одном щелчке начали двигаться и выстроились в строку, что-то вроде анимации. Вместо этого перемещение происходит после каждого щелчка. Анимацию я запихнула в class/object, она нужна для каждой буквы. Пример кода.
<!DOCTYPE HTML>
<html>
    <head>
	<title>Animation move</title>
  <meta charset="utf-8">
</head>
    <body>
     <canvas id="canvas1" width="670" height="500" style="background-color:#eee; border:1px solid #ccc;"></canvas>
     
    <script>
 var canvas1, context; 

var pred = [];
var str = "Тестовый пример!";

var rect;

function myUp(e){
   i = 0;
   clear();
    for (;;) 
    {
        if (i >= pred.length) 
        {
            return;
        }
        pred[i].animate(pred[i].x,pred[i].y);
        pred[i].draw(context);
       
        ++i;
    }
    
}




StringObj = function(str,x,y,xtr)
{
   this.str = str;
   this.x = x;
   this.y = y;
   this.xtr = xtr;
   this.start1 = performance.now();

   this.draw = function(ctx)
   {
   
      ctx.font = "22px Verdana";
      ctx.fillText(this.str, this.x, this.y);
      
   }
   this.animate = function(x,y) {
     var xtr = this.xtr;
     this.x = x;
     this.y = y;
     var self = this;
   //Аниация
   requestAnimationFrame(animate1 = now => {
        let progress = now - self.start1;
       
        if (progress > 1000) {
            
            self.start1 += 1000;
            self.x = self.x + (self.xtr - self.x) / 10; 
            self.y = self.y + (100 - self.y) / 10;
            self.animate(self.x,self.y);
        };
       self.animate(self.x,self.y);
   });  
   }
   
}
function draw() {
  clear();

  i = 0;
  while (i <  pred.length) 
  {
   
    pred[i].draw(context); 
 
     ++i;
  }
}



function clear() {
  context.clearRect(0, 0, canvas1.width, canvas1.height);

}

function init() {
    canvas1 = document.getElementById("canvas1");
    context = canvas1.getContext("2d");
    var j = 0;
    var xtr = 0;
     while (j < str.length) 
    {
        
       if(j>0)
       {
         xtr = xtr + context.measureText(str[j-1]).width;
       }
       else
       {
         xtr = 200;
       }
        rect = new StringObj(str[j],Math.random()*canvas1.width,Math.random()*canvas1.height,xtr);
        pred.push(rect);
        ++j;
    }
   draw();


    
    document.addEventListener("click",function(evt)
    { 
      myUp(evt);
    });
   

}
  init();
    </script>
   </body>
</html>

Последний раз редактировалось Katy93, 28.05.2021 в 21:38.
Ответить с цитированием