Bootstrap

canvas 画录音波形图

随机数获取音量大小

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title></title>
</head>
<style>
    * {
        padding: 0;
        margin: 0;
    }

    #myCanvas {
        width: 100%;
    }
</style>

<body>

    <canvas id="myCanvas" width="1000" height="300" style="border-bottom:1px solid #d3d3d3">
        您的浏览器不支持 HTML5 canvas 标签。</canvas>

    <script>

        var c = document.getElementById("myCanvas");
        var ctx = c.getContext("2d");
        ctx.translate(500, 150)
        var grad = ctx.createLinearGradient(-500, -150, -500, 150);
        grad.addColorStop(0, "red");
        grad.addColorStop(0.5, "blue");
        grad.addColorStop(1, "yellow");
        ctx.lineWidth = 1;

        function init(val) {
            // ctx.fillStyle = "#f00"
            // ctx.fillRect(-400, -150, 800, 300)
            ctx.clearRect(-400, -150, 1000, 300)
            ctx.beginPath()
            let m = 10
            let n = 3
            let len = 100
            let ran = 16
            ran = Math.random() * 100
            // ran = val
            console.log(ran);
            for (let i = len; i > 0; i--) {
                let x = -(i * m)
                // ran = Math.sin(ran * 10 * Math.PI / 180) * 60
                let y1 = (ran - i / 2) * n
                let y2 = -(ran - i / 2) * n
                // let y1 = Math.sin((ran - i) / 1) * 300
                // let y2 = -Math.sin((ran - i) / 1) * 300

                if (y1 < 0) y1 = 0
                if (y2 > 0) y2 = 0
                if (y1 > len) y1 = len
                if (y2 < -len) y2 = -len

                ctx.moveTo(x, y1);
                ctx.lineTo(x, y2);
            }
            for (let i = 0; i < len; i++) {
                let x = i * m
                // ran = Math.sin(ran * 10 * Math.PI / 180) * 60
                // console.log(ran);
                let y1 = (ran - i / 2) * n
                let y2 = -(ran - i / 2) * n
                // let y1 = Math.sin((ran - i)) * 100
                // let y2 = -Math.sin((ran - i)) * 100
                // console.log(y1, y2);

                if (y1 < 0) y1 = 0
                if (y2 > 0) y2 = 0
                if (y1 > len) y1 = len
                if (y2 < -len) y2 = -len

                ctx.moveTo(x, y1);
                ctx.lineTo(x, y2);

            }
        }
        init(4)
        ctx.strokeStyle = grad;
        ctx.stroke();

    </script>

</body>

</html>

效果图

 

 

;