html掉落本地图片效果

实现一个加载本地图片并掉落的html页面。


说明

DuanWu.htmlzongzi_1.png, zongzi_2.png, zongzi_3.png, yadan.png4张图片放在同一个目录下,然后双击打开DuanWu.html即可。

  • 使用ChromeMicrosoft Edge浏览器打开

  • 若使用IE浏览器打开,下方会出现Internet Explorer已限制此网页运行脚本或ActiveX控件。,请点击右边允许阻止的内容(A)


代码

DuanWu.html

DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>本地图片飘落效果title>
    <style>
        body {
            background-color: #1a6840;
            overflow: hidden;
        }

        canvas {
            display: block;
            position: absolute;
            top: 0;
            left: 0;
        }
    style>
head>

<body>
    <canvas id="canvas">canvas>
    <script>
        var canvas = document.getElementById('canvas');
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        var ctx = canvas.getContext('2d');
        var leaves = [];
        var numLeaves = 28;
        images = loadImages()
        function loadImages() {
            images = []
            images[0] = new Image()
            images[0].src = "zongzi_1.png"
            images[1] = new Image()
            images[1].src = "zongzi_2.png"
            images[2] = new Image()
            images[2].src = "zongzi_3.png"
            images[3] = new Image()
            images[3].src = "yadan.png"
            return images
        }
        function createLeaf(image) {
            this.x = Math.random() * canvas.width;
            this.y = -100;
            this.vx = Math.random() * 2 - 1;
            this.vy = Math.random() * 3 + 1;
            this.draw = function () {
                ctx.drawImage(image, this.x, this.y, image.width, image.height);
            }
            this.update = function () {
                this.x += this.vx;
                this.y += this.vy;
                if (this.y > canvas.height + 10) {
                    this.y = -10;
                    this.x = Math.random() * canvas.width;
                }
            }
        }
        function init() {
            for (var i = 0; i < numLeaves; i++) {
                leaves.push(new createLeaf(images[i % images.length]));
            }
        }
        function loop() {
            requestAnimationFrame(loop);
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            for (var i = 0; i < numLeaves; i++) {
                leaves[i].draw();
                leaves[i].update();
            }
        }

        init();
        loop();
    script>
body>

html>

参考

HTML5实现的树叶飘落动画特效

HTML5 Canvas显示本地图片实例1、Canvas预览图片实例1

中国色


图片

zongzi_1.png
zongzi_2.png
zongzi_3.png
yadan.png

你可能感兴趣的:(前端,html,前端,canvas)