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>
相关推荐
Lazy_zheng几秒前
Map / Set / WeakMap / WeakSet,一次给你讲透
前端·javascript·面试
learyuan几秒前
Windows原生开发
前端
uzong3 分钟前
ClaudeCode 入门详细教程,手把手带你Vibe Coding
前端·人工智能
英俊潇洒美少年13 分钟前
前端安全 完整精讲
前端·安全
aircrushin14 分钟前
2026我最推荐的前端设计skills
前端
problc15 分钟前
Pretext —— 无 DOM 文本测量与布局引擎
前端·ai
阿kun要赚马内17 分钟前
Python面向对象:@property装饰器
开发语言·前端·python
徒 花19 分钟前
web前端技术知识复习
前端·html·web
意法半导体STM3231 分钟前
【官方原创】STM32H7双核芯片通过 STlink连接失败问题分析 LAT1654
开发语言·前端·javascript·stm32·单片机·嵌入式硬件
小王C语言32 分钟前
【基础IO】————简单设计一下libc库
前端·数据结构·算法