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>
相关推荐
weixin1997010801611 分钟前
《电天下商品详情页前端性能优化实战》
前端·性能优化
速易达网络12 分钟前
vue+echarts开发的图书数字大屏系统
前端
小智社群21 分钟前
贝壳获取小区的名称
开发语言·前端·javascript
Ferries37 分钟前
《从前端到 Agent》系列|03:应用层-RAG(检索增强生成,Retrieval-Augmented Generation)
前端·人工智能·机器学习
Jessica_Lee42 分钟前
Openclaw智能体终止机制
javascript
米丘44 分钟前
Connect 深度解析:Node.js 中间件框架的基石
javascript·http·node.js
饺子不吃醋44 分钟前
执行上下文:变量提升、作用域与 this 底层机制
javascript
菲利普马洛1 小时前
记一次主题闪烁问题
前端·css·react.js
谁在黄金彼岸1 小时前
nvm for windows之死:别再被这个“过时工具”耽误开发
前端
汉堡大王95271 小时前
为了搞懂 Promise 源码,我重写了 MiniPromise
前端·javascript