# Canvas动画

2019/7/23 14:06:36 人评论 次浏览 分类：学习教程

### 2：基本步骤

• 绘制 - 清空 - 绘制 - 清空 - 绘制 …

### 3：控制函数

• setTimeout
• setInterval
• requestAnimationFrame

### 4：四种运动

#### 线性运动

``````    const canvas = document.getElementById('canvas');
/* 获得 2d 上下文对象 */
const ctx = canvas.getContext('2d');

let distance = -50;
const speed = 5;

const draw = (axisX) => {
/* 清空画布(或部分清空) */
ctx.clearRect(0, 0, 600, 600);

ctx.beginPath();
ctx.moveTo(distance, 300);
ctx.arc(distance, 300, 50, 0, 2 * Math.PI, false);
ctx.fill();

distance = distance + speed;

if (distance > 650) distance = -50;

requestAnimationFrame(draw);
}

requestAnimationFrame(draw);ctx.clearRect(0, 0, 600, 600);

ctx.beginPath();
ctx.moveTo(distance, 300);
ctx.arc(distance, 300, 50, 0, 2 * Math.PI, false);
ctx.fill();

distance = distance + speed;
``````

#### 变速运动

``````    const canvas = document.getElementById('canvas');
/* 获得 2d 上下文对象 */
const ctx = canvas.getContext('2d');

let distance = 50;
const speed = 5;

let count = 1;

/*
* h = 9.8 * (Math.pow(t, 2)) / 2
*/

const draw = (axisX) => {
/* 清空画布(或部分清空) */
ctx.clearRect(0, 0, 600, 600);

ctx.beginPath();
ctx.moveTo(300, distance);
ctx.arc(300, distance, 50, 0, 2 * Math.PI, false);
ctx.fill();

count += 1;

distance = 9.8 * (Math.pow(count, 2)) / 100;
if (distance > 650) {
distance = -50;
count = 1;
}

requestAnimationFrame(draw);
}

requestAnimationFrame(draw);
``````

#### 函数运动（正弦）

``````    const canvas = document.getElementById('canvas');
/* 获得 2d 上下文对象 */
const ctx = canvas.getContext('2d');

let distance = 0;
let axis = 300;
const speed = 5;

const range = 200;

let angle = 0;

const draw = (axisX) => {
/* 清空画布(或部分清空) */
// ctx.clearRect(0, 0, 600, 600);

ctx.beginPath();
ctx.moveTo(distance, axis);
ctx.arc(distance, axis, 50, 0, 2 * Math.PI, false);
ctx.fill();

axis = 300 + Math.sin(angle) * range;

distance = distance + speed;
if (distance > 650) {
distance = 0;
angle = -.1;
}

angle += .1;
requestAnimationFrame(draw);
}

requestAnimationFrame(draw);
``````

#### 环形运动

``````    const canvas = document.getElementById('canvas');
/* 获得 2d 上下文对象 */
const ctx = canvas.getContext('2d');

let angle = 0.1;
var scope = 20;

let x = 300;
let y = 100;

const draw = (axisX) => {
/* 清空画布(或部分清空) */
ctx.clearRect(0, 0, 600, 600);
ctx.beginPath();
ctx.moveTo(x, y);
ctx.arc(x, y, 50, 0, 2 * Math.PI, false);
ctx.fill();

x = x + Math.cos(angle) * scope;
y = y + Math.sin(angle) * scope;
angle = angle + .1;

requestAnimationFrame(draw);
ctx.closePath();

ctx.beginPath();
ctx.arc(300, 300, 200, 0, 2 * Math.PI, false);
ctx.stroke();
}

requestAnimationFrame(draw);
``````

暂无相关的资讯...

-->