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);
    })();

脈衝運動

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章