javascript - 包含 'shaking' 效果的 HTML Canvas 动画

标签 javascript jquery html canvas

我有一个使用 Canvas 创建的动画。动画快要完成了,它显示了爆炸。我想知道是否有一种方法可以创造一种震动效果,当爆炸发生时, Canvas 上的内容看起来好像在震动几秒钟。

感谢任何帮助。

最佳答案

摇动屏幕的一种简单方法是在每次绘制之前将整个上下文平移到随机方向。
您必须保存/恢复上下文以使其保持“干净”状态。

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>

关于javascript - 包含 'shaking' 效果的 HTML Canvas 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28023696/

相关文章:

javascript - 将敏感信息保留在 JavaScript 代码中的安全缺陷

javascript - jQuery : Want to disable all the input fields if editqastatus value = 1 or 2

javascript - 外部元素在外部 ng-repeat 中访问数据

html - 光标在区域中保持指针

javascript - 在没有按键事件的情况下检测 CTRL 和 SHIFT 键?

javascript - 简单类测试未通过

Javascript - 将顶部样式从 "ul"更改为 div 父项的子项

javascript - 在 flex-box 中使用 javascript 管理图像

javascript - .attr ("value") 总是返回未定义?

html - 面包屑箭头 rtl 方向