3

散是满天星,聚是一把火!_周杰伦本人的技术博客_51CTO博客

 1 year ago
source link: https://blog.51cto.com/u_15460453/5680448
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

散是满天星,聚是一把火!

据说很多大厂都在让自己的员工毕业,毕业不可怕,散是满天星,聚是一把火!今天我就用canvas给大家实现聚是一团火,散是满天星的功能,安慰一下大家。

那么这个效果是怎么实现的呢?

首先我们定义画布,这里就不多说了

<canvas id="jay" width="600" height="600"></canvas>

接下来就是JavaScript的实现了

思路是这样的

第一步 写出🔥这个特殊字符来

let weight = 600, height = 600;
ctxJay.font = '300px 草书';
ctxJay.fillStyle = '#000';
ctxJay.textAlign = 'center';
ctxJay.fillText('🔥', weight / 2, height / 2, weight);

这段代码就是通过canvas来写出火这个特殊字符来

第二步 定义点对象 拆分字符

第二步都是把这个字符进行拆分一个一个点的对象,我们通过getImageData()方法来获取像素点,获取到所有的数据后,for循环遍历:

for (let y = 0; y < height; y += 3) {
    for (let x = 0; x < weight; x += 3) {
        let index = x + y * weight;
        let result = copy.data[index * 4 + 3];
        if (result > 128) {
            let point = new Point(x, y);
            pointArray.push(point);
            point.show();
        }
    }
  }

这里像素点128值的判断依据是像素点的值是0-255之间,0表示表示完成透明,255表示可见,因为我们取中间值来判断是不是火这个元素的像素点

取出像素点包装成一个Point对象,放入数组中。

第三步 定时执行画小火苗

第三步就是利用setInterval()方法定时画圆就可以了

setInterval(function () {
    ctxJay.clearRect(0, 0, weight, height);
    for (let i = 0; i < pointArray.length; i++) {
        pointArray[i].show();
    }

}, 180);

具体是调用像素点对象的show()方法:

Point.prototype.show = function () {
        this.x += this.xSpeed;
        this.y += this.ySpeed;
        ctxJay.beginPath();
        ctxJay.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
        ctxJay.fillStyle = this.color;
        ctxJay.fill();
        ctxJay.closePath();
    };

这里的x y 就是一个一个的小火苗的位置,x y的其实位置是随机的,当最终位置是确定的,就是我们在第一步获取的像素点的位置,这样就实现了随机位置到固定位置的变化,从而每个像素点聚集在一起,形成一团火的效果

这篇文章主要用canvas实现了聚是一团火,散是满天星的效果,其中使用了面向对象的思想,把一个个像素点放入Point对象中,并利用了定时任务的方法,很有意思,canvas的操作其实和数学物理学有所牵连。你也来试试吧!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK