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>
相关推荐
林恒smileZAZ2 小时前
Vue<前端页面版本检测>
前端·javascript·vue.js
码事漫谈6 小时前
当AI开始“思考”:我们是否真的准备好了?
前端·后端
许杰小刀6 小时前
ctfshow-web文件包含(web78-web86)
android·前端·android studio
我是Superman丶7 小时前
Element UI 表格某行突出悬浮效果
前端·javascript·vue.js
恋猫de小郭7 小时前
你的代理归我了:AI 大模型恶意中间人攻击,钱包都被转走了
前端·人工智能·ai编程
xiaokuangren_7 小时前
前端css颜色
前端·css
Huanzhi_Lin7 小时前
关于V8/MajorGC/MinorGC——性能优化
javascript·性能优化·ts·js·v8·新生代·老生代
hoiii1878 小时前
C# 基于 LumiSoft 实现 SIP 客户端方案
前端·c#
anOnion8 小时前
构建无障碍组件之Meter Pattern
前端·html·交互设计
小码哥_常8 小时前
Spring Boot配置diff:解锁配置管理新姿势
前端