Using JavaScript or jQuery, how can I get the RGB color when the mouse moves specifically in the <img> or <div> elements
I have an image, <img src="/meAndMy/face.jpg" /> . I am trying to get an RGB color when ever or somewhere I move the mouse cursor.
How can I do this using jQuery or regular JavaScript? for example: http://www.script-tutorials.com/demos/158/index.html
Follow-up steps (for copy testing):
<?=$this->headScript(); ?> <script> $(document).ready(function() { var image = new Image(); var ctx = $('#panel')[0].getContext("2d"); /* Load the picture empty.jpg */ image.onload = function () { ctx.drawImage(image, 0, 0, image.width, image.height); } /* How can i reload later new? image.empty; */ image.src = "/agents/empty.jpg"; /* On mouse over to my image, show me the background with RGB change mousemove to click if requires */ $('#panel').mousemove(function(e) { /* Leave as it is */ var canvasOffset = $(this).offset(); var canvasX = Math.floor(e.pageX - canvasOffset.left); var canvasY = Math.floor(e.pageY - canvasOffset.top); var imageData = ctx.getImageData(canvasX, canvasY, 1, 1); var pixel = imageData.data; var pixelColor = "rgba("+pixel[0]+", "+pixel[1]+", "+pixel[2]+", "+pixel[3]+")"; /* Meat */ $(document.body).css('background-color',pixelColor); }); }); </script> <body> <canvas id="panel" width="500" height="333"></canvas> <body> You can do this the same way as the script for this demo. Please note that the demo does not use the img element, but loads the image into the canvas element. The canvas API allows you to get pixel data as follows:
var imageData = ctx.getImageData(canvasX, canvasY, 1, 1); var pixel = imageData.data; See the HTML 5 canvas API for more details.
If for some reason you need to load the image into the img element, unlike the canvas element, you can:
- Dynamically create a canvas element with the same size and in the same place as img.
- Copy image data from img to canvas using the drawImage method from the canvas context.
- Hide the img element, leaving the canvas in its place.
You cannot get the color of an image point using JavaScript only (without Canvas support). You need the server side.
For example: you have a jpg image. You point somewhere, click. The event listener should send the coordinates to the server, and the server application will determine what the color is (the image should be present on the server, of course). see http://muffinresearch.co.uk/code/javascript/pickr/
In your example, the image is read and displayed by the canvas element. The event listener gets the click coordinates and getImageData () gets a copy of the pixel. The property contains information about red, green, blue, and alpha components.