HTML Canvas动画包含了一个“摇动”的动画。影响

时间:2015-01-19 11:32:26

标签: javascript jquery html5 canvas

我有一个使用canvas创建的动画。动画几乎完成,它显示爆炸。我想知道是否有办法创造一种震动效果,好像爆炸发生时画布的内容会震动几秒钟。

任何帮助表示感谢。

1 个答案:

答案 0 :(得分:12)

摇动屏幕的一种简单方法是在每次抽奖前以随机方向翻译整个上下文 您必须保存/恢复上下文以使其保持“干净”状态。

var ctx=cv.getContext('2d');

function preShake() {
  ctx.save();
  var dx = Math.random()*10;
  var dy = Math.random()*10;
  ctx.translate(dx, dy);  
}

function postShake() {
  ctx.restore();
}

function drawThings() {  
  ctx.fillStyle = '#F00';
  ctx.fillRect(10, 10, 50, 30);
  ctx.fillStyle = '#0F0';
  ctx.fillRect(140, 30, 90, 110);
  ctx.fillStyle = '#00F';
  ctx.fillRect(80, 70, 60, 40);
}

drawThings();

function animate() {
  // keep animation alive
  requestAnimationFrame(animate);
  // erase
  ctx.clearRect(0,0,cv.width, cv.height);
  //
  preShake();
  //
  drawThings();
  //
  postShake();
}

animate();
  <canvas id='cv'></canvas>

请注意,您可能更喜欢使用一些sin函数和一些缓动来获得更平滑的效果:

var ctx=cv.getContext('2d');

var shakeDuration = 800;
var shakeStartTime = -1;

function preShake() {
  if (shakeStartTime ==-1) return;
  var dt = Date.now()-shakeStartTime;
  if (dt>shakeDuration) {
      shakeStartTime = -1; 
      return;
  }
  var easingCoef = dt / shakeDuration;
  var easing = Math.pow(easingCoef-1,3) +1;
  ctx.save();  
  var dx = easing*(Math.cos(dt*0.1 ) + Math.cos( dt *0.3115))*15;
  var dy = easing*(Math.sin(dt*0.05) + Math.sin(dt*0.057113))*15;
  ctx.translate(dx, dy);  
}

function postShake() {
  if (shakeStartTime ==-1) return;
  ctx.restore();
}

function startShake() {
   shakeStartTime=Date.now();
}

function drawThings() {  
  ctx.fillStyle = '#F00';
  ctx.fillRect(10, 10, 50, 30);
  ctx.fillStyle = '#0F0';
  ctx.fillRect(140, 30, 90, 110);
  ctx.fillStyle = '#00F';
  ctx.fillRect(80, 70, 60, 40);
}

drawThings();

function animate() {
  // keep animation alive
  requestAnimationFrame(animate);
  // erase
  ctx.clearRect(0,0,cv.width, cv.height);
  //
  preShake();
  //
  drawThings();
  //
  postShake();
}

startShake();
setInterval(startShake,2500);
animate();
  <canvas id='cv'></canvas>