Anime.js使用画布添加相应的动画

时间:2018-11-10 15:41:09

标签: javascript canvas anime.js

我正在尝试使用Julian示例之一的修改版,使用canvas和Anime.js进行简单的交互。想法是,圆圈将在屏幕上放大,然后用户单击屏幕上的任意位置,圆圈将收缩。我无法播放第二个动画,不确定这是因为我的目标无效还是与时间轴有关?这是示例。

//Canvas set up

var canvas = document.querySelector('.gameCanvas');
var ctx = canvas.getContext('2d');
var pointerX = 0;
var pointerY = 0;
var circle;
let basicTimeline = anime.timeline();


function setCanvasSize() {
  canvas.width = window.innerWidth * 2;
  canvas.height = window.innerHeight * 2;
  canvas.style.width = window.innerWidth + 'px';
  canvas.style.height = window.innerHeight + 'px';
  canvas.getContext('2d').scale(2, 2);
}

//Objects and animation

function createCircle(x,y) {
    var p = {};
    p.x = x;
    p.y = y;
    p.color = "#fff";
    p.radius = anime.random(16, 32);
    p.alpha = .5;
    p.draw = function() {
      ctx.globalAlpha = p.alpha;
      ctx.beginPath();
      ctx.arc(p.x, p.y, p.radius, 0, 2 * Math.PI, true);
      ctx.fillStyle = p.color;
      ctx.fill();
    }
    return p;
}

function renderParticle(anim) {
  for (var i = 0; i < anim.animatables.length; i++) {
    anim.animatables[i].target.draw();
  }
}

function createExpandCircle(x, y) {
    circle = createCircle(x, y);
    basicTimeline.add({
        targets: circle,
        radius: anime.random(80, 160),
        alpha: {
            value: 1,
            easing: 'linear',
            duration: anime.random(600, 800),  
        },
        duration: anime.random(1200, 1800),
        easing: 'linear',
        update: renderParticle,
        offset: 0
    });

}

function contractCircle(){
    basicTimeline.add({
        targets: circle,
        radius: 20,
        easing: 'easeOutExpo'
        update: renderParticle
    });

}

//Mouse Events

var tap = ('ontouchstart' in window || navigator.msMaxTouchPoints) ? 'touchstart' : 'mousedown';

function updateCoords(e) {
  pointerX = e.clientX || e.touches[0].clientX;
  pointerY = e.clientY || e.touches[0].clientY;
}

document.addEventListener(tap, function(e) {
  updateCoords(e);
  contractCircle();
  }, false);

var centerX = window.innerWidth / 2;
var centerY = window.innerHeight / 2;

createExpandCircle(centerX, centerY);
setCanvasSize();
window.addEventListener('resize', setCanvasSize, false);

1 个答案:

答案 0 :(得分:0)

因此我能够通过添加以下内容来解决此问题:

ctx.clearRect(0, 0, canvas.width, canvas.height);

要绘制,然后

basicTimeline = anime.timeline();

要收缩圈子。