Javascript.RU

Создать новую тему Ответ
 
Опции темы Искать в теме
  #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.
Ответить с цитированием
  #2 (permalink)  
Старый 28.05.2021, 22:08
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,072

Katy93,
run добавьте в тег форматирования
Ответить с цитированием
  #3 (permalink)  
Старый 28.05.2021, 23:37
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,072

canvas text move
Katy93,
<!DOCTYPE html>
<html>

<head>
    <title>Untitled</title>
    <meta charset="utf-8">
    <style type="text/css">
        .text {
            background-color: #eee;
            border: 1px solid #ccc;
        }
    </style>
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            class letter {
                constructor(text, x, y) {
                    this.text = text;
                    this.x = x;
                    this.y = y;
                }
            }
            class canvasTextMove extends letter {
                constructor(...args) {
                    super(...args);
                    this.canvas = canvas;
                    this.context = this.canvas.getContext("2d");
                    this.rip = 12;
                    this.width = this.canvas.width - this.rip * 2;
                    this.height = this.canvas.height - this.rip * 2;
                    this.letter = [...this.text].map((txt, i) => new letter(txt, ...this.position()));
                    this.letter.forEach(this.draw.bind(this))
                    this.canvas.addEventListener("click", function() {
                        this.beginTime = performance.now();
                        requestAnimationFrame(this.loop.bind(this));
                    }.bind(this), {
                        once: true
                    })
                }
                rnd(num) {
                    return Math.trunc(Math.random() * num)
                }
                position() {
                    return [this.rnd(this.width), this.rnd(this.height)]
                }
                draw({ text, x, y }) {
                    this.context.font = "22px monospace";
                    this.context.fillText(text, x, y);
                }
                loop(time) {
                    this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
                    if (time - this.beginTime < 1600) {
                        this.letter.forEach((letter, i) => {
                            letter.x += (this.x + (i * this.rip) - letter.x) * .05;
                            letter.y += (this.y - letter.y) * .05;
                            this.draw(letter);
                        })
                        requestAnimationFrame(this.loop.bind(this))
                    } else this.draw(this);
                }
            }
            let canvas = document.querySelector(".text");
            new canvasTextMove("Тестовый пример!", 230, 120, canvas)
        });
    </script>
</head>

<body>
    <canvas class="text" width="670" height="500" style=""></canvas>
</body>

</html>

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



Опции темы Искать в теме
Искать в теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Как сделать, чтобы прогресс бар отработал не один раз, а несколько? Lefseq Общие вопросы Javascript 3 29.02.2020 13:14
Как сделать, чтобы русские буквы не вводились в определенные поля формы? yachainik Общие вопросы Javascript 6 13.02.2017 16:43
как сделать чтобы в popup окне показывалось картинка? sarik Общие вопросы Javascript 31 15.03.2013 13:12
как сделать так чтобы в popup окне принимался css стили,? sarik Общие вопросы Javascript 2 12.03.2013 10:24
Как сделать паузу после загрузки страницы? denisOgr AJAX и COMET 2 06.08.2011 15:01