首页 > 解决方案 > Anime.js 使用画布添加相应的动画

问题描述

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

//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);

标签: javascriptcanvasanime.js

解决方案


所以我能够通过添加以下内容来解决这个问题:

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

p.draw,和

basicTimeline = anime.timeline();

去契约圈。


推荐阅读