Using JavaScript or jQuery, how can I get the RGB color where ever the mouse is moving specially in >

前端 未结 2 579
醉酒成梦
醉酒成梦 2020-12-10 07:35

I have an image, . I am trying to get the RGB color when ever or where ever I move my mouse cursor.

How can I do

相关标签:
2条回答
  • 2020-12-10 08:06

    You can't get the color of point of an image only with JavaScript ( without the Canvas support ). You need some server-side.

    For example: you have a jpg image. You point somewhere, click. An event-listener should send to the server the coordinates and a server-side 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/

    For your example - the image is read and displayed by a canvas element. An event-listener gets the coordinates of the click and with getImageData() gets a copy of the pixel. The data property contains info for a red, green, blue, and alpha component.

    0 讨论(0)
  • 2020-12-10 08:07

    You can do it just like the script for that demo does. Note that the demo does not use an img element, rather it loads the image into a canvas element. The canvas API allows you to get the pixel data like so:

    var imageData = ctx.getImageData(canvasX, canvasY, 1, 1);
    var pixel = imageData.data;
    

    See the HTML 5 canvas API for details.

    If for whatever reason you are required to load the image into the img element, as opposed to a canvas element, you could:

    1. Dynamically create a canvas element with the same size and at the same location as the img.
    2. Copy the image data from img to canvas via the drawImage method from the canvas context.
    3. Hide the img element, leaving the canvas in its place.
    0 讨论(0)
提交回复
热议问题