2013-06-22 29 views

回答

0

您無法通過JavaScript訪問背景圖像的像素數據。你將不得不做的是創建一個新的圖像對象,並將源設置爲背景圖片URL。之後,你將不得不做這些步驟:

  • 創建內存畫布對象
  • 畫在畫布上
  • 獲取圖像數據的圖像,通過所有像素迭代和顏色存儲在一個對象(鍵=顏色,值= repitition量)
  • 排序陣列由repitition的量,然後選擇第一值

在這裏,我創建了一個例子。這會加載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";