原生js实现canvas火焰

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<meta http-equiv="X-UA-Compatible" content="ie=edge">

<title>Document</title>

<style>

html {

overflow: hidden;

touch-action: none;

-ms-content-zooming: none;

/* content-zooming: none; */

}

body {

position: absolute;

margin: 0;

padding: 0;

width: 100%;

height: 100%;

background: #1D1E22;

}

canvas {

position: absolute;

margin: auto;

top: 0;

right: 0;

bottom: 0;

left: 0;

width: 200px;

height: 400px;

border-radius: 4px;

background: #000;

cursor: none;

}

</style>

</head>

<body>

<canvas></canvas>

<script>

"use strict";

const W = 40;

const H = 80;

const S = 5;

const mtx = new Uint16Array((W + 1) * H);

const canvas = document.querySelector("canvas");

const ctx = canvas.getContext("2d", {lowLatency: true, alpha: false});

canvas.width = W * S;

canvas.height = H * S;

let xm = 20;

let ym = 74;

const move = (e) => {

    let p = e;

    if (e.type === "touchmove") {

        e.preventDefault();

        p = e.targetTouches[0];

    }

    xm = Math.round((p.clientX - canvas.offsetLeft) / S);

    ym = Math.round((p.clientY - canvas.offsetTop) / S);

}

canvas.addEventListener("mousemove", move, false);

canvas.addEventListener("touchmove", move, false);

const flame = () => {

    requestAnimationFrame(flame);

    if(xm > 1 && xm < W - 1 && ym > 1 && ym < H - 1){

        mtx[ym * W + xm] = 0 + 8192 * Math.random();

    }

    for(let i = 1; i < H - 1; i++) {

        for(let j = 1; j < W - 1; j++) {

            const p = i * W + j;

            const ap = p + W - Math.round(Math.random());

            const ncb = mtx[p];

            const nc = Math.round((mtx[ap] + mtx[ap + 1] + mtx[ap - W] + mtx[ap - W + 1]) * 0.485 * Math.random());

            mtx[p] = nc;

            if (nc !== ncb) {

                const z = -ym + i;

                ctx.fillStyle = `rgb(${Math.round(nc * 4)}, ${Math.round(nc * 2)},${Math.round(nc * 0.001 * z * z * z)})`;

                ctx.fillRect(j * S, i * S, S - 1, S - 1);

            }

        }

    }

}

flame();

</script>

</body>

</html>

猜你喜欢

转载自blog.csdn.net/duyujian706709149/article/details/85765433