Canvas波形运动

小球类

class Ball{
	constructor(obj) {
		this.x = obj.x;
		this.y = obj.y;
		this.r = obj.r;
		this.scaleX = 1;
		this.scaleY = 1;
		this.color = '#E685FF';
	}
	draw(ctx){
		ctx.save();
		ctx.translate(this.x, this.y);
		ctx.scale(this.scaleX, this.scaleY);
		ctx.beginPath();
		//这里的X,Y都是原点的位置, 主要是通过上面的translate的来控制圆心的位置
		ctx.arc(0, 0, this.r, 0, Math.PI *2);
		ctx.fillStyle = this.color;
		ctx.fill();
		ctx.restore();
		return this;
	}
}

平滑运动

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
    * {
        padding: 0;
        margin: 0;
    }

    #canvas {
        box-shadow: 0 0 20px #ccc;
    }
    </style>
</head>

<body>
    <canvas id="canvas" width="800" height="500"></canvas>
    <script src="ball.js"></script>
    <script>
    let canvas = document.getElementById('canvas');
    let ctx = canvas.getContext('2d');
    let W = canvas.width;
    let H = canvas.height;

    let ball = new Ball({
        x: W / 2,
        y: H / 2,
        r: 45
    }).draw(ctx);
    let angle = 0;
    const SWING = 160; //(振幅)因为sin的取值范围在[-1,1],移动范围就很小, 就乘上一个固定值,这样每次移动的范围就大一些
    (function move(){
    	window.requestAnimationFrame(move);
    	ctx.clearRect(0, 0, W, H);
    	ball.x = W / 2 + Math.sin(angle) * SWING;
    	angle += 0.05;
    	angle %= Math.PI * 2;
    	ball.draw(ctx);
    })()
    </script>
</body>

</html>  

平滑运动

线性运动

let canvas = document.getElementById('canvas');
    let ctx = canvas.getContext('2d');
    let W = canvas.width;
    let H = canvas.height;

    let ball = new Ball({
        x: 100,
        y: H / 2,
        r: 30
    }).draw(ctx);
    let angle = 0;
    
    let vx = 2;
    const SWING = 100; //(振幅)因为sin的取值范围在[-1,1],移动范围就很小, 就乘上一个固定值,这样每次移动的范围就大一些
    (function move(){
    	window.requestAnimationFrame(move);
    	ctx.clearRect(0, 0, W, H);
    	ball.x += vx;
    	ball.y = H / 2 + Math.sin(angle) * SWING;
    	angle += 0.05;
    	angle %= Math.PI * 2;
    	ball.draw(ctx);
    })()

线性运动

脉冲运动


let canvas = document.getElementById('canvas');
    let ctx = canvas.getContext('2d');
    let W = canvas.width;
    let H = canvas.height;

    let ball = new Ball({
        x: W / 2,
        y: H / 2,
        r: 50
    }).draw(ctx);
    let angle = 0;
    
    let initScale = 1;
    const SWING = 0.5; //(振幅)因为sin的取值范围在[-1,1],移动范围就很小, 就乘上一个固定值,这样每次移动的范围就大一些
    (function move(){
    	window.requestAnimationFrame(move);
    	ctx.clearRect(0, 0, W, H);
    	ball.scaleX = ball.scaleY = initScale + Math.sin(angle) * SWING;
    	angle += 0.05;
    	angle %= Math.PI * 2;
    	ball.draw(ctx);
    })();

脉冲运动

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值