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>
相关推荐
toooooop83 分钟前
Vuex Store实例中`state`、`mutations`、`actions`、`getters`、`modules`这几个核心配置项的区别
前端·javascript·vue.js
LYFlied6 分钟前
Rust代码打包为WebAssembly二进制文件详解
开发语言·前端·性能优化·rust·wasm·跨端
OpenTiny社区10 分钟前
历时1年,TinyEditor v4.0 正式发布!
前端·javascript·vue.js
time_rg15 分钟前
深入理解react——1. jsx与虚拟dom
前端·react.js
Keke16 分钟前
🍔 fabric如何实现辅助选区捏
前端·javascript
weixin_4368040716 分钟前
图片在线预览工具 - 输入URL即刻查看远程图片
html·媒体
hang_bro17 分钟前
echarts 饼图显示设置
前端·echarts
2501_9418868618 分钟前
基于法兰克福金融系统实践的高可靠消息队列设计与多语言实现经验总结分享
服务器·前端·数据库
用户120391129472619 分钟前
React 性能优化之道:useMemo、useCallback 与闭包陷阱的深度剖析
前端·javascript·react.js
niconicoC22 分钟前
Three.js 高性能天气效果实现:下雨与下雪的 GPU 粒子系统
前端