首页 文章详情

当初男票就是用 canvas 画一场流星雨把我追到手的

Java研发军团 | 441 2020-12-01 18:52 0 0 0
UniSMS (合一短信)

开始

妹子都喜欢流星,如果她说不喜欢,那她一定是一个假妹子。

现在就一起来做一场流星雨,用程序员的野路子浪漫一下。

要画一场流星雨,首先,自然我们要会画一颗流星。

玩过 canvas 的同学,你画圆画方画线条这么 6,如果说叫你画下面这个玩意儿,你会不会觉得你用的是假 canvas?canvas 没有画一个带尾巴玩意儿的 api 啊。

画一颗流星

是的,的却是没这个 api,但是不代表我们画不出来。流星就是一个小石头,然后因为速度过快产生大量的热量带动周围的空气发光发热,所以经飞过的地方看起来就像是流星的尾巴,我们先研究一下流星这个图像,整个流星处于他自己的运动轨迹之中,当前的位置最亮,轮廓最清晰,而之前划过的地方离当前位置轨迹距离越远就越暗淡越模糊。

上面的分析结果很关键, canvas 上是每一帧就重绘一次,每一帧之间的时间间隔很短。流星经过的地方会越来越模糊最后消失不见,那有没有可以让画布画的图像每过一帧就变模糊一点而不是全部清除的办法?如果可以这样,就可以把每一帧用线段画一小段流星的运动轨迹,最后画出流星的效果。

骗纸!你也许会说,这那里像流星了???

别急,让我多画几段给你看看。

什么?还是不像?我们把它画小点,这下总该像了把?

上面几幅图我是在 ps 上模拟的,本质上 ps 也是在画布上绘画,我们马上在 canvas 上试试。

那,直接代码实现一下。

  1. // 坐标

  2. class Crood {

  3.    constructor(x=0, y=0) {

  4.        this.x = x;

  5.        this.y = y;

  6.    }

  7.    setCrood(x, y) {

  8.        this.x = x;

  9.        this.y = y;

  10.    }

  11.    copy() {

  12.        return new Crood(this.x, this.y);

  13.    }

  14. }



  15. // 流星

  16. class ShootingStar {

  17.    constructor(init=new Crood, final=new Crood, size=3, speed=200, onDistory=null) {

  18.        this.init = init; // 初始位置

  19.        this.final = final; // 最终位置

  20.        this.size = size; // 大小

  21.        this.speed = speed; // 速度:像素/s



  22.        // 飞行总时间

  23.        this.dur = Math.sqrt(Math.pow(this.final.x-this.init.x, 2) + Math.pow(this.final.y-this.init.y, 2)) * 1000 / this.speed;



  24.        this.pass = 0; // 已过去的时间

  25.        this.prev = this.init.copy(); // 上一帧位置

  26.        this.now = this.init.copy(); // 当前位置

  27.        this.onDistory = onDistory;

  28.    }

  29.    draw(ctx, delta) {

  30.        this.pass += delta;

  31.        this.pass = Math.min(this.pass, this.dur);



  32.        let percent = this.pass / this.dur;



  33.        this.now.setCrood(

  34.            this.init.x + (this.final.x - this.init.x) * percent,

  35.            this.init.y + (this.final.y - this.init.y) * percent

  36.        );



  37.        // canvas

  38.        ctx.strokeStyle = '#fff';

  39.        ctx.lineCap = 'round';

  40.        ctx.lineWidth = this.size;

  41.        ctx.beginPath();

  42.        ctx.moveTo(this.now.x, this.now.y);

  43.        ctx.lineTo(this.prev.x, this.prev.y);

  44.        ctx.stroke();



  45.        this.prev.setCrood(this.now.x, this.now.y);

  46.        if (this.pass === this.dur) {

  47.            this.distory();

  48.        }

  49.    }

  50.    distory() {

  51.        this.onDistory && this.onDistory();

  52.    }

  53. }





  54. // effet

  55. let cvs = document.querySelector('canvas');

  56. let ctx = cvs.getContext('2d');



  57. let T;

  58. let shootingStar = new ShootingStar(

  59.                        new Crood(100, 100),

  60.                        new Crood(400, 400),

  61.                        3,

  62.                        200,

  63.                        ()=>{cancelAnimationFrame(T)}

  64.                    );



  65. let tick = (function() {

  66.    let now = (new Date()).getTime();

  67.    let last = now;

  68.    let delta;

  69.    return function() {

  70.        delta = now - last;

  71.        delta = delta > 500 ? 30 : (delta < 16? 16 : delta);

  72.        last = now;

  73.        // console.log(delta);



  74.        T = requestAnimationFrame(tick);



  75.        ctx.save();

  76.        ctx.fillStyle = 'rgba(0,0,0,0.2)'; // 每一帧用 “半透明” 的背景色清除画布

  77.        ctx.fillRect(0, 0, cvs.width, cvs.height);

  78.        ctx.restore();

  79.        shootingStar.draw(ctx, delta);

  80.    }

  81. })();

  82. tick();

效果:一颗流星

sogoyi 快看,一颗活泼不做作的流星!!! 是不是感觉动起来更加逼真一点?

流星雨

我们再加一个流星雨 MeteorShower 类,生成多一些随机位置的流星,做出流星雨。

  1. // 坐标

  2. class Crood {

  3.    constructor(x=0, y=0) {

  4.        this.x = x;

  5.        this.y = y;

  6.    }

  7.    setCrood(x, y) {

  8.        this.x = x;

  9.        this.y = y;

  10.    }

  11.    copy() {

  12.        return new Crood(this.x, this.y);

  13.    }

  14. }



  15. // 流星

  16. class ShootingStar {

  17.    constructor(init=new Crood, final=new Crood, size=3, speed=200, onDistory=null) {

  18.        this.init = init; // 初始位置

  19.        this.final = final; // 最终位置

  20.        this.size = size; // 大小

  21.        this.speed = speed; // 速度:像素/s



  22.        // 飞行总时间

  23.        this.dur = Math.sqrt(Math.pow(this.final.x-this.init.x, 2) + Math.pow(this.final.y-this.init.y, 2)) * 1000 / this.speed;



  24.        this.pass = 0; // 已过去的时间

  25.        this.prev = this.init.copy(); // 上一帧位置

  26.        this.now = this.init.copy(); // 当前位置

  27.        this.onDistory = onDistory;

  28.    }

  29.    draw(ctx, delta) {

  30.        this.pass += delta;

  31.        this.pass = Math.min(this.pass, this.dur);



  32.        let percent = this.pass / this.dur;



  33.        this.now.setCrood(

  34.            this.init.x + (this.final.x - this.init.x) * percent,

  35.            this.init.y + (this.final.y - this.init.y) * percent

  36.        );



  37.        // canvas

  38.        ctx.strokeStyle = '#fff';

  39.        ctx.lineCap = 'round';

  40.        ctx.lineWidth = this.size;

  41.        ctx.beginPath();

  42.        ctx.moveTo(this.now.x, this.now.y);

  43.        ctx.lineTo(this.prev.x, this.prev.y);

  44.        ctx.stroke();



  45.        this.prev.setCrood(this.now.x, this.now.y);

  46.        if (this.pass === this.dur) {

  47.            this.distory();

  48.        }

  49.    }

  50.    distory() {

  51.        this.onDistory && this.onDistory();

  52.    }

  53. }



  54. class MeteorShower {

  55.    constructor(cvs, ctx) {

  56.        this.cvs = cvs;

  57.        this.ctx = ctx;

  58.        this.stars = [];

  59.        this.T;

  60.        this.stop = false;

  61.        this.playing = false;

  62.    }



  63.    createStar() {

  64.        let angle = Math.PI / 3;

  65.        let distance = Math.random() * 400;

  66.        let init = new Crood(Math.random() * this.cvs.width|0, Math.random() * 100|0);

  67.        let final = new Crood(init.x + distance * Math.cos(angle), init.y + distance * Math.sin(angle));

  68.        let size = Math.random() * 2;

  69.        let speed = Math.random() * 400 + 100;

  70.        let star = new ShootingStar(

  71.                        init, final, size, speed,

  72.                        ()=>{this.remove(star)}

  73.                    );

  74.        return star;

  75.    }



  76.    remove(star) {

  77.        this.stars = this.stars.filter((s)=>{ return s !== star});

  78.    }



  79.    update(delta) {

  80.        if (!this.stop && this.stars.length < 20) {

  81.            this.stars.push(this.createStar());

  82.        }

  83.        this.stars.forEach((star)=>{

  84.            star.draw(this.ctx, delta);

  85.        });

  86.    }



  87.    tick() {

  88.        if (this.playing) return;

  89.        this.playing = true;



  90.        let now = (new Date()).getTime();

  91.        let last = now;

  92.        let delta;



  93.        let  _tick = ()=>{

  94.            if (this.stop && this.stars.length === 0) {

  95.                cancelAnimationFrame(this.T);

  96.                this.playing = false;

  97.                return;

  98.            }



  99.            delta = now - last;

  100.            delta = delta > 500 ? 30 : (delta < 16? 16 : delta);

  101.            last = now;

  102.            // console.log(delta);



  103.            this.T = requestAnimationFrame(_tick);



  104.            ctx.save();

  105.            ctx.fillStyle = 'rgba(0,0,0,0.2)'; // 每一帧用 “半透明” 的背景色清除画布

  106.            ctx.fillRect(0, 0, cvs.width, cvs.height);

  107.            ctx.restore();

  108.            this.update(delta);

  109.        }

  110.        _tick();

  111.    }



  112.    start() {

  113.        this.stop = false;

  114.        this.tick();

  115.    }



  116.    stop() {

  117.        this.stop = true;

  118.    }  

  119. }



  120. // effet

  121. let cvs = document.querySelector('canvas');

  122. let ctx = cvs.getContext('2d');



  123. let meteorShower = new MeteorShower(cvs, ctx);

  124. meteorShower.start();

效果:流星雨

透明背景

先不急着激动,这个流星雨有点单调,可以看到上面的代码中,每一帧,我们用了透明度为 0.2 的黑色刷了一遍画布,背景漆黑一片,如果说我们的需求是透明背景呢?

比如,我们要用这个夜景图片做背景,然后在上面加上我们的流星,我们每一帧刷一层背景的小伎俩就用不了啦。因为我们要保证除开流星之外的部分,应该是透明的。

这里就要用到一个冷门的属性了,globalCompositeOperation,全局组合操作?原谅我放荡不羁的翻译。

这个属性其实就是用来定义后绘制的图形与先绘制的图形之间的组合显示效果的。 

他可以设置这些值

这些属性说明没必要仔细看,更不用记下来,直接看 api 示例 运行效果就很清楚了。示例里,先绘制的是填充正方形,后绘制的是填充圆形。

是不是豁然开朗,一目了然?

对于我们来说,原图像是每一帧画完的所有流星,目标图像是画完流星之后半透明覆盖画布的黑色矩形。而我们每一帧要保留的就是,上一帧 0.8 透明度的流星,覆盖画布黑色矩形我们不能显示。

注意这里的 destination-out 和 destination-in,示例中这两个属性最终都只有部分源图像保留了下来,符合我们只要保留流星的需求。我觉得 w3cschool 上描述的不是很正确,我用我自己的理解概括一下。

  • destination-in :只保留了源图像(矩形)和目标图像(圆)交集区域的源图像

  • destination-out:只保留了源图像(矩形)减去目标图像(圆)之后区域的源图像

上述示例目标图像的透明度是 1,源图像被减去的部分是完全不见了。而我们想要的是他可以按照目标透明度进行部分擦除。改一下示例里的代码看看是否支持半透明的计算。

看来这个属性支持半透明的计算。源图像和目标图像交叠的部分以半透明的形式保留了下来。也就是说如果我们要保留 0.8 透明度的流星,可以这样设置 globalCompositeOperation

  1. ctx.fillStyle = 'rgba(0,0,0,0.8)'

  2. globalCompositeOperation = 'destination-in';

  3. ctx.fillRect(0, 0, cvs.width, cvs.height);





  4. // 或者

  5. ctx.fillStyle = 'rgba(0,0,0,0.2)'

  6. globalCompositeOperation = 'destination-out';

  7. ctx.fillRect(0, 0, cvs.width, cvs.height);

最终效果

加上 globalCompositeOperation 之后的效果既最终效果:

快约上你的妹子看流星雨吧。

...

什么?你没有妹子?

源自:https://segmentfault.com/a/1190000008664249

声明:文章著作权归作者所有,如有侵权,请联系小编删除


点击原文阅读获得原创整理:《第2版:互联网大厂面试题》


good-icon 0
favorite-icon 0
收藏
回复数量: 0
    暂无评论~~
    Ctrl+Enter