html js 动画效果,javascript – 包含“摇动”效果的HTML 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,cv.width,cv.height);

//

preShake();

//

drawThings();

//

postShake();

}

animate();

请注意,您可能更喜欢使用一些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,cv.height);

//

preShake();

//

drawThings();

//

postShake();

}

startShake();

setInterval(startShake,2500);

animate();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值