美文网首页
canvas简单动画--躁动的小球

canvas简单动画--躁动的小球

作者: LinDaiDai_霖呆呆 | 来源:发表于2017-09-21 08:53 被阅读87次

前言

我们都知道canvas实际就是一个H5新增的标签,它呢,可以用来制作照片集或者制作简单(也不是那么简单)的动画,甚至可以进行实时视频处理和渲染。
制作动画的原理实际上也非常简单:
利用定时执行一定语句的方法来重复执行绘图功能,
常用的方法有:
1. setInterval()
2. setTimeout()
3. requestAnimationFrame()

一个简单的demo

在讲解躁动的小球之前呢,我们先来看一个简单的动画:

让一个方块以匀速向右移动

<canvas id="canvas" width="400" height="400" style="border: 1px solid #000">您的浏览器不支持</canvas>
<script>
        //获取canvas
        let canvas = document.querySelector('#canvas')
        //获取2d的上下文对象
        let cxt = canvas.getContext('2d')
        //创建一个方块对象
        let rect = {
            w:50,   //宽
            h:50,   //高
            x:20,   //x轴方向的位移
            y:0,    //y方向的位移
            color:'red',    //填充色
        }
        //给方块对象中添加绘制的方法
        rect.draw=function(){
            //每调用一次这个函数执行一次x+2的操作
            this.x += 2
            cxt.fillStyle = this.color
            cxt.fillRect(this.x, this.y, this.w, this.h)
        }

        setInterval(function () {
            //绘图之前先清空画布,如果不清空的话,就会看到一连串的方块
            ctx.clearRect(0, 0, canvas.width, canvas.height)
            //调用绘制方块的函数
            rect.draw()
        },30)
</script>

上面的例子我们可以看到,我先创建了一个rect对象,这个对象中储存的是绘制的方块的各种信息,如宽高,位移,颜色等.
然后给rect对象添加一个绘制的功能(draw),其中这个功能中将this.x累加,
最后在外面利用一个没30毫秒执行一次的定时器来调用rect.draw(),这样就实现了让方块一直向右运动的效果(有一点要注意,在每次调用绘制方法之前,都得清空当前的画布)
清空画布的方法:
clearRect(startX,startY,endX,endY)
第一,二个参数表示的是清空的其实位置,后俩个位置表示清空的结束位置.
这里我想清空的是整个画布,也就是其实位置从(0,0)点开始,结束位置就是整个画布的宽度和高度(画布的最右下角).

躁动的小球

好的,说完上面的例子,我就可以来介绍这篇文章的主要内容,"躁动的小球",我们先来看下效果图:

image.png

可以看到,效果就是在画布中,绘制出各种颜色不同,透明度不同的小球,并且这些小球是可以四处乱窜的.

1. 布局

先来看看布局,实际是布局上很简单,就是一个class为out的div内盛放一个<canvas>

<div class="out">
    <canvas id="canvas" width="1000" height="600"></canvas>
</div>

而在样式上内,我是这样设定的:

<style>
        *{
            padding: 0;
            margin: 0;
        }
        body{
            background-color: #333333;
        }
        .out{
            height: 600px;
            width: 1000px;
            margin: 50px auto;
            box-shadow: 2px 2px 10px #999;
        }
    </style>

2. JS部分

<script>
    /**
     * 创建一个小球的构造函数
     * @param canvasW   画布的宽
     * @param canvasH   画布的高
     * @param ctx       2d上下文
     * @constructor
     */
    function Ball(canvasW, canvasH, ctx) {
        this.canvasW = canvasW
        this.canvasH = canvasH
        this.ctx = ctx
        this.r = this.randomInt(10, 80)
        this.x = this.randomInt(this.r, this.canvasW - this.r)
        this.y = this.randomInt(this.r, this.canvasH - this.r)

        let R = this.randomInt(0, 255)
        let G = this.randomInt(0, 255)
        let B = this.randomInt(0, 255)
        let A = Math.random()
        this.color = `rgba(${R},${G},${B},${A})`

        let speedX = this.randomInt(1, 4)
        this.speedX = this.randomInt(0, 100) > 50 ? speedX : -speedX
        let speedY = this.randomInt(1, 4)
        this.speedY = this.randomInt(0, 100) > 50 ? speedY : -speedY
    }
    //绘制一个小球
    Ball.prototype.draw = function () {
        let deg = Math.PI / 180
        this.ctx.beginPath()
        this.ctx.arc(this.x, this.y, this.r, 0, 360 * deg, true)
        this.ctx.closePath()
        this.ctx.fillStyle = this.color
        this.ctx.fill()
    }

    //小球移动
    Ball.prototype.ballMove = function () {
        this.x += this.speedX
        this.y += this.speedY

        if (this.x >= this.canvasW - this.r) {
            this.speedX *= -1
        } else if (this.x <= this.r) {
            this.speedX *= -1
        }

        if (this.y >= this.canvasH - this.r) {
            this.speedY *= -1
        } else if (this.y <= this.r) {
            this.speedY *= -1
        }
    }

    //产生范围随机数的函数
    Ball.prototype.randomInt = function (from, to) {
        return parseInt(Math.random() * (to - from + 1) + from);
    }

    let canvas = document.querySelector('#canvas');
    let ctx = canvas.getContext('2d')
    //定义一个数组用来盛放所有的小球"对象"
    let balls = []
    for (let i = 0; i < 100; i++) {
        let ball = new Ball(canvas.width, canvas.height, ctx);
        balls.push(ball)
    }

    setInterval(function () {
        //绘图之前先清空画布
        ctx.clearRect(0, 0, canvas.width, canvas.height)
        for (let i = 0; i < balls.length; i++) {
            balls[i].ballMove();
            balls[i].draw()
        }
    }, 30)
</script>

1.也是和上面的demo一样,我想将每一个小球都当成一个"对象"来写,只不过小球的数量不确定,所以我写了一个构造函数Ball,用它来创建每一个小球对象,这样只要利用一个for循环,就可以创建我们想要的数量的小球了.
2.这里的绘制小球和移动小球我分别用了俩个函数draw()ballMove()来写,这样的目的能也是为了达到面向对象的效果,将各个功能拆分开来,一个方法实现一种功能.
3.利用for循环来重复调用构造函数Ball,每创建一个小球"对象",就把它推进数组balls中,这样for循环完之后,balls数组中存放的就是一个个的小球"对象".
4.利用定时器setInterval,每隔30毫秒,调用一次ballMove()draw()

相关文章

网友评论

      本文标题:canvas简单动画--躁动的小球

      本文链接:https://www.haomeiwen.com/subject/ndzasxtx.html