美文网首页
canvas ImageData读取图片属性使用

canvas ImageData读取图片属性使用

作者: 小灰灰_a | 来源:发表于2021-09-25 18:07 被阅读0次

代码中用到了 getImageData方法,具体参考[https://www.w3school.com.cn/tags/canvas_getimagedata.asp]

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>getImageData</title>
</head>

<body>

    <canvas id="canvas" width="1500px" height="400px"></canvas>
    <button onclick="change()">变色</button>

    <script>

        let color = document.getElementById('grad')
        let img = new Image();
        let canvas = document.getElementById('canvas')
        let ctx = canvas.getContext('2d')
        img.src = 'http://p1.music.126.net/TzMwwPWS6lONrPqOiOrZFw==/109951165693801980.jpg'
        img.crossOrigin = "anonymous"
        img.onload = function () {
            ctx.drawImage(img, 0, 0)
        }

        const change = () => {
            let imgData = ctx.getImageData(0, 0, img.width, img.height)
            const proxy = new Proxy(imgData, {
                get: (obj, prop) => {
                    return obj[prop]
                },
                set: (obj, prop, value) => {
                    obj[prop] = value;
                    return true
                }
            })
            let data = imgData.data;
            for (let i = 0; i < data.length; i += 4) {
                let avg = (data[i] + data[i + 1] + data[i + 2]) / 3;  // 修改图片色值
                avg = avg > 220 ? 0 : avg;
                data[i] = avg; // red
                data[i + 1] = avg; // green
                data[i + 2] = avg; // blue
            }
            console.log(data);
            const reImg = new ImageData(data, proxy.width, proxy.height);
            ctx.putImageData(reImg, 0, 0)
        }

    </script>


</body>

</html>

相关文章

网友评论

      本文标题:canvas ImageData读取图片属性使用

      本文链接:https://www.haomeiwen.com/subject/jptcnltx.html