Javascript-大多数重复背景图像上的像素

Javascript-大多数重复背景图像上的像素,javascript,image,pixels,Javascript,Image,Pixels,如何在背景图像中找到最重复的像素并找出颜色? 救命啊 您无法通过JavaScript访问背景图像的像素数据。您需要做的是创建一个新的图像对象,并将源设置为背景图像URL。之后,您必须执行以下步骤: 创建内存中的画布对象 在画布上绘制图像 获取图像数据,遍历所有像素并将颜色存储在对象中(键=颜色,值=重复次数) 按重复次数对数组排序,然后选择第一个值 在这里,我创建了一个示例。这将加载JSconf徽标,并将主体的背景色设置为最重复的颜色 // Create the image var imag

如何在背景图像中找到最重复的像素并找出颜色?
救命啊

您无法通过JavaScript访问背景图像的像素数据。您需要做的是创建一个新的图像对象,并将源设置为背景图像URL。之后,您必须执行以下步骤:

  • 创建内存中的画布对象
  • 在画布上绘制图像
  • 获取图像数据,遍历所有像素并将颜色存储在对象中(键=颜色,值=重复次数)
  • 按重复次数对数组排序,然后选择第一个值
在这里,我创建了一个示例。这将加载JSconf徽标,并将主体的背景色设置为最重复的颜色

// Create the image
var image = new Image();
image.crossOrigin = "Anonymous";

image.onload = function () {
    var w = image.width, h = image.height;

    // Initialize the in-memory canvas
    var canvas = document.createElement("canvas");
    canvas.width = w;
    canvas.height = h;

    // Get the drawing context
    var context = canvas.getContext("2d");

    // Draw the image to (0,0)
    context.drawImage(image, 0, 0);

    // Get the context's image data
    var imageData = context.getImageData(0, 0, w, h).data;

    // Iterate over the pixels
    var colors = [];
    for(var x = 0; x < w; x++) {
        for(var y = 0; y < h; y++) {
            // Every pixel has 4 color values: r, g, b, a
            var index = ((y * w) + x) * 4;

            // Extract the colors
            var r = imageData[index];
            var g = imageData[index + 1];
            var b = imageData[index + 2];

            // Turn rgb into hex so we can use it as a key
            var hex = b | (g << 8) | (r << 16);

            if(!colors[hex]) {
                colors[hex] = 1;
            } else {
                colors[hex] ++;   
            }
        }
    }

    // Transform into a two-dimensional array so we can better sort it
    var _colors = [];
    for(var color in colors) {
        _colors.push([color, colors[color]]);   
    }

    // Sort the array
    _colors.sort(function (a, b) {
        return b[1] - a[1]; 
    });

    var dominantColorHex = parseInt(_colors[0][0]).toString(16);
    document.getElementsByTagName("body")[0].style.backgroundColor = "#" + dominantColorHex;
};

image.src = "http://upload.wikimedia.org/wikipedia/commons/thumb/6/6a/JavaScript-logo.png/600px-JavaScript-logo.png";
//创建图像
var image=新图像();
image.crossOrigin=“匿名”;
image.onload=函数(){
var w=image.width,h=image.height;
//初始化内存画布
var canvas=document.createElement(“canvas”);
画布宽度=w;
canvas.height=h;
//获取图形上下文
var context=canvas.getContext(“2d”);
//将图像绘制到(0,0)
drawImage(image,0,0);
//获取上下文的图像数据
var imageData=context.getImageData(0,0,w,h).data;
//在像素上迭代
var颜色=[];
对于(变量x=0;x