HTML Canvas 动画,加入“抖动”效果

8
我有一个使用canvas创建的动画,它几乎完成了,并显示了一次爆炸。我想知道是否有一种方法可以创建一种震动效果,当爆炸发生时,画布的内容似乎会在几秒钟内晃动。

非常感谢您的帮助。


你可以使用context.translate(x,y)函数,其中x和y默认为0,用于确定画布的原点(左上角)。如果在重新绘制之前更改这些值,您可以让画布通过y++向下移动或通过x--向左移动。如果足够快地执行此操作,它会产生震动效果。 - dwana
1个回答

19
一个简单的使屏幕抖动的方法是在每次绘制之前将整个上下文随机方向翻译一遍。
您需要保存/恢复上下文以保持其处于“清洁”状态。

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>

请注意,您可能希望使用一些正弦函数和缓动效果来获得更加平滑的效果:

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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接