使用canvas画闪闪星光

    选择打赏方式

突发奇想写了一写

效果图  点击查看效果

2019-11-16 14.15.05.gif

第一步创建html结构


<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<div>
    <canvas id="canvas" height="600" width="800"></canvas>
    <script type="text/javascript" src="./js/main.js"></script>
    <script type="text/javascript" src="./js/star.js"></script>
</div>
</body>
</html>
第二部写js文件


main.js


let can;
let ctx;
let w;
let h;
let img = new Image();
let jpgimage = new Image();
let num = 5;
let starArr = []
document.body.onload = () => {
    can = document.getElementById('canvas')
    ctx = can.getContext('2d');
    w = can.width;
    h = can.height;
    jpgimage.src = 'src/IMG_2727 0.jpg'
    img.src = 'src/star.png'
    for (let i = 0 ; i < num; i++ ) {
        starArr.push(new StarObj)
        starArr[i].draw()
    }
    gameloop()
}

function drawBackground() {
    ctx.fillStyle = '#303550';
    ctx.fillRect(0,0, w, h)

    console.log('1')
}

function gameloop() {
    window.requestAnimFrame(gameloop)
    drawBackground();
    drawJpg()
    for (let i of starArr) {
        i.draw()
    }
}

window.requestAnimFrame = (function(){
    return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function( callback ){
            window.setTimeout(callback, 1000 / 60);//定义每秒执行60次动画
        };
})();

const drawJpg = () => {
    // console.log(this)
    ctx.drawImage(jpgimage, 100, 100, 600, 350)
}
start.js



class StarObj{
    constructor() {
        this.x = Math.floor(Math.random() * can.width);
        this.y = Math.floor(Math.random() * can.height);
        this.lastTime = Date.now();
        this.timer = 0;
        this.n = Math.floor(Math.random() * 7);
    }
    update() {
        let space = Date.now() - this.lastTime;
        this.lastTime = Date.now();
        this.timer = space + this.timer;
        if (this.timer > 50) {
            this.n++;
            this.timer = 0;
            if (this.n > 7) {
                this.n = 0;
            }
        }
    }
    draw() {
        this.update()
        ctx.drawImage(img, this.n * 7, 0, 7, 7, this.x, this.y, 7, 7)
    }
}


版权声明:若无特殊注明,本文皆为《 张宇童 》原创,转载请保留文章出处。
本文链接:使用canvas画闪闪星光 https://www.zyt8.cn/h/232.html
正文到此结束

热门推荐

发表吐槽

你肿么看?

你还可以输入 250 / 250 个字

嘻嘻 大笑 可怜 吃惊 害羞 调皮 鄙视 示爱 大哭 开心 偷笑 嘘 奸笑 委屈 抱抱 愤怒 思考 日了狗 胜利 不高兴 阴险 乖 酷 滑稽

评论信息框

吃奶的力气提交吐槽中...


既然没有吐槽,那就赶紧抢沙发吧!