html根据图片变换背景色

html根据图片变换背景色

javascript 复制代码
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title></title>
    <style>
        .item {
            width: 50%;
            height: 80vh;
            margin: 0 auto;
            border: 1px solid red;
        }
    </style>
</head>

<body>
    <img src="./img/1.png" alt="" style="width: 200px;height: 200px;border: 1px solid red;">
    <script>
        // Load the image
        const img = new Image();
        img.src = './img/1.png';

        // Wait for the image to load
        img.onload = function () {
            // Create a canvas element
            const canvas = document.createElement('canvas');
            canvas.width = img.width;
            canvas.height = img.height;

            // Draw the image onto the canvas
            const ctx = canvas.getContext('2d');
            ctx.drawImage(img, 0, 0);

            // Get the dominant color of the image
            const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
            const colors = {};
            for (let i = 0; i < imageData.data.length; i += 4) {
                const r = imageData.data[i];
                const g = imageData.data[i + 1];
                const b = imageData.data[i + 2];
                const color = `${r},${g},${b}`;
                if (colors[color]) {
                    colors[color]++;
                } else {
                    colors[color] = 1;
                }
            }
            const dominantColor = Object.keys(colors).reduce((a, b) => colors[a] > colors[b] ? a : b);

            // Set the background color of the webpage to the dominant color
            document.body.style.backgroundColor = `rgb(${dominantColor})`;
        };
    </script>

</body>

</html>
相关推荐
light blue bird5 分钟前
设备数据变化上传图表数据汇总组件
大数据·前端·信息可视化
2501_9181269111 分钟前
开源祭祖网页index
前端·开源·html
threelab23 分钟前
Three.js 3D 饼图效果 | 三维可视化 / AI 提示词
javascript·人工智能·3d
傻瓜搬砖人1 小时前
SpringMVC的请求
java·前端·javascript·spring
木易 士心1 小时前
为什么 Promise 比 setTimeout 先执行?——JavaScript 事件循环与异步顺序完全指南
开发语言·javascript·ecmascript
爱上好庆祝1 小时前
学习js的第六天(js基础的结束)
开发语言·前端·javascript·学习·ecmascript
yqcoder1 小时前
JS 类型检测双雄:typeof vs instanceof 深度解析
开发语言·javascript·ecmascript
IT_陈寒1 小时前
JavaScript的异步地狱,我差点没爬出来
前端·人工智能·后端
光影少年1 小时前
Webpack打包性能优化方面的经验
前端·webpack·性能优化
Das11 小时前
通过命令行下载kaggle数据
前端·chrome