Get pixelcolor of CSS Background Image

前端 未结 1 1799
有刺的猬
有刺的猬 2020-12-21 22:40

I need to get the color of any pixel my mousepointer is currently hovering. I found several solutions for canvas elements, but none for a background image defined in CSS fo

1条回答
  •  盖世英雄少女心
    2020-12-21 23:39

    Combining the answers from Get a CSS value with JavaScript and How to get a pixel's x,y coordinate color from an image?, I was able to simulate what you are looking for: JSFiddle

    
    
        
        
    
    
        

    I retrieved the computed style (var style = window.getComputedStyle(div);) outside of the mouse move function for performance reasons, but if the background image is going to change dynamically, then it may need to be moved into the function.

    There are some possible browser constraints for using getComputedStyle.

    SCALING You could try editing the code to adjust for the scale:

    var h = parseInt(style.getPropertyValue("width")), 
        w = parseInt(style.getPropertyValue("height"));
    
    var img = document.getElementById("i1");
    img.src = path;
    
    var canvas = document.getElementById("c1");
    canvas.width = h;
    canvas.height = w;
    canvas.getContext('2d').drawImage(img, 0, 0, w, h);
    

    This also includes a change to the CSS: JSFiddle

    0 讨论(0)
提交回复
热议问题