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>
相关推荐
~无忧花开~6 分钟前
React事件处理全解析
开发语言·前端·javascript·react.js·前端框架
英俊潇洒美少年7 分钟前
豆包官方开放 API 调用指南(合法稳定版)
前端·javascript
KevinCyao9 分钟前
批量发短信接口的数据格式设计:CSV、JSON还是XML?
xml·前端·前端框架·json
英俊潇洒美少年10 分钟前
React Fiber = 任务切片 + 时间切片
前端·react.js·前端框架
漠月瑾-西安10 分钟前
JavaScript 字符串处理技巧:substring 与 indexOf 的灵活组合
javascript·前端开发·indexof·代码优化·substring·字符串处理
2501_9383134012 分钟前
用Python实现自动化的Web测试(Selenium)
前端·python·自动化
Mintopia12 分钟前
React vs Vue 优势对比Demo(证明React更具优势)
前端·vue.js·react.js
2501_9419820515 分钟前
进阶指南:如何基于自动化能力进行企业通讯工具接口的二次开发
前端·机器人·自动化·企业微信·rpa
Mintopia16 分钟前
PR 才是主战场:AI 时代的 Code Review 新规则
前端·人工智能
海上彼尚17 分钟前
Nuxt4 官网访问来源统计的实现
开发语言·前端·javascript