canvas动画部分

requestAnimationFrame(callback)

一个用于制作逐帧动画的函数

//这个函数会在控制台无限输出"----"
(function animate() {
    requestAnimationFrame(animate);
    console.log("----");
})();
ctx.arc(100,100,40,0,Math.PI*2,false);
ctx.stroke();
(function animate() {
    requestAnimationFrame(animate);
    //在同一个坐标无限循环画一个圆
    //重新定义开始坐标,试着注释掉这一行看看效果有何不同
    ctx.beginPath();
    ctx.arc(100,100,40,0,Math.PI*2,false);
    ctx.stroke();
})();

很多圆叠加在一起,尝试修改位置:

//初始化坐标
let x = 100;
let y = 100;
(function animate() {
    requestAnimationFrame(animate);
    //重新定义开始坐标,试着注释掉这一行看看效果有何不同
    ctx.beginPath();
    ctx.arc(x,y,40,0,Math.PI*2,false);
    ctx.stroke();
    //动态修改坐标
    x += 1;
    y += 1;
})();

前面的圆没有清除,所以需要每次都清除画布,使用橡皮擦函数 clearRect(x坐标,y坐标,宽度,高度):

let x = 100;
let y = 100;
(function animate() {
    requestAnimationFrame(animate);
    //这是我们加入的橡皮擦函数
    ctx.clearRect(0,0,innerWidth,innerHeight);
    ctx.beginPath();
    ctx.arc(x,y,40,0,Math.PI*2,false);
    ctx.stroke();
    x += 1;
    y += 1;
})();

圆在动,但是超出范围就看不到了,制作弹性效果

//我把参数都设为变量
let x = Math.random()*innerWidth;// 横坐标
let y = Math.random()*innerHeight;// 纵坐标
let r = Math.random()*40; // 半径
let dx = Math.random()*6; // 横向平移距离
let dy = Math.random()*6; // 纵向平移距离
(function animate() {
    requestAnimationFrame(animate);
    ctx.clearRect(0,0,innerWidth,innerHeight);
    ctx.beginPath();
    ctx.arc(x,y,r,0,Math.PI*2,false);
    ctx.stroke();
    //当触及边界时进行反弹
    // 当触及边界时
    if(x+r>innerWidth || x-r<0) {
        dx=-dx;
    }
    if(y+r>innerHeight || y-r<0) {
        dy=-dy;
    }

    x += dx;
    y += dy;
})(); 

实现多个圆:

//圆的数组
let circleArray = [];
//循环制造不同的圆,存进数组
for(let i=0;i<100;i++){
    let x = Math.random()*innerWidth;// 横坐标
    let y = Math.random()*innerHeight;// 纵坐标
    let r = Math.random()*40; // 半径
    let dx = Math.random()*6; // 横向平移距离
    let dy = Math.random()*6; // 纵向平移距离
    circleArray.push(new Circle(x,y,r,dx,dy));
}


// 创建一个Circle对象
function Circle(x,y,r,dx,dy) {
    this.x = x;
    this.y = y;
    this.r = r;
    this.dx = dx;
    this.dy = dy;

    // 绘制圆
    this.draw = function() {
        ctx.beginPath();
        ctx.arc(x,y,r,0,Math.PI*2,false);
        ctx.stroke();
    }
    // 更新圆的位置
    this.update = function() {
        x+=dx;
        y+=dy;    
        // 当触及边界时
        if(x+r>innerWidth || x-r<0) {
            dx=-dx;
        }
        if(y+r>innerHeight || y-r<0) {
            dy=-dy;
        }
        // 每一次更新都要重新在一个新的地方绘制圆
        this.draw();
    }
}

// 这个函数会在控制台无限输出"canvas"
function animate() {
    requestAnimationFrame(animate);
    // 橡皮擦函数 clearRect(x坐标,y坐标,宽度,高度)
    ctx.clearRect(0,0,innerWidth,innerHeight);
    // 循环刷新每个圆
    for(let i=0;i<circleArray.length;i++){
        circleArray[i].update();
    }
}
animate();
原文地址:https://www.cnblogs.com/biubiuxixiya/p/8144768.html