How to find the most repetitive pixels in the background-image and find out the color? help!
You do not have access to background image pixel data via javascript. What you have to do, create a new image object and set the background image URL to the source. Afterwards, you have to do these steps:
- Create an in-memory canvas object
- Drag the image to the canvas
- Get the image data, Store the colors again and in one object through all the pixels (key = color, value = amount of the repatition)
- Sort the array with the amount of reconstruction, then select the first value
Here, I have created an example that loads the JSCong logo and the body Sets the background color of r in most repetitive colors.
// image vs image = create new image (); Image.crossOrigin = "Anonymous"; Image.onload = function () {var w = image.width, h = image.height; // Start In-Memory Canvas Vans Canvas - document.createElement ("Canvas"); Canvas.width = w; Canvas.height = h; // Get the drawing reference var context = canvas.gatecontax ("2D"); Draw in image (0,0) context.drawImage (image, 0, 0); // Receive image data of the reference var imageData = context.getImageData (0, 0, w, h). Data; //Itrate on pixel var colors = []; (Var x = 0; x & lt; w; x ++) {for (var y = 0; y and lt; h; y ++) {// Every pixel has 4 color values: r, g , B, a var index = ((Y * w) + x) * 4; // Remove the colors var r = image data [index]; Var g = imageData [index + 1]; Var B = ImageData [index + 2]; // Turn RGB into hex so that we can use it as a major var hex = b (G & lt; <8). (R & lt; & lt; 16); If (! Color [hex]) {color [hex] = 1; } And {color [hex] ++; }}} Turns into a two-dimensional array so that we get it better _colors = []; (Different colors in colors) {_colors.push ([color, color [color]]); } // Sort the array _colors.sort (function (a, b) {return b [1] - a [1];}); Var major color = hex = 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";
No comments:
Post a Comment