我有一个使用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>
请注意,您可能希望使用一些正弦函数和缓动效果来获得更加平滑的效果:
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>