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>
相关推荐
全栈小510 分钟前
【前端】Vue 组件开发中的枚举值验证:从一个Type属性错误说起
前端·javascript·vue.js
Joker Zxc13 分钟前
【前端基础(Javascript部分)】4、JavaScript的分支语句
开发语言·前端·javascript
IT_陈寒17 分钟前
JavaScript 性能优化的5个隐藏技巧:90%开发者都不知道的实战方案!
前端·人工智能·后端
꧁꫞꯭零꯭点꯭꫞꧂44 分钟前
G6绘制机柜 以及机柜设备的demo
前端·javascript·vue.js
C澒1 小时前
供应链产研交付提效:前端多业务线新增样板间页面统计方案
前端·mr
可视之道1 小时前
低代码可视化平台的前端架构设计:从渲染引擎到插件系统
前端
南城书生1 小时前
Android Kotlin 协程原理分析
前端
Lee川1 小时前
🚀 JavaScript 内存大揭秘:从“栈堆搬家”到“闭包时空胶囊”
前端·javascript·面试
唐叔在学习1 小时前
TodoList应用:SPA应用首屏性能优化实践
前端·javascript·性能优化
恋猫de小郭1 小时前
AI 时代的工程师需要具备什么能力?Augment Code 给出了他们的招聘标准
前端·人工智能·ai编程