Development Tip

JavaScript 스포이드 (마우스 커서 아래의 픽셀 색상 표시)

yourdevel 2020. 11. 14. 11:11
반응형

JavaScript 스포이드 (마우스 커서 아래의 픽셀 색상 표시)


CMS 용 JavaScript에서 마우스 커서가있는 픽셀의 16 진수 값을 제공 하는 " 스포이드 "도구를 찾고 있습니다.

Firefox의 경우이를 정확히 수행하는 뛰어난 ColorZilla 확장 기능이 있습니다. 하지만 당연히 FF 일 뿐이며 CMS와 함께 도구를 제공하고 싶습니다.

네덜란드 개발자는 Ajax와 PHP의 조합을 사용 하여 이미지의 픽셀 색상을 찾는 매우 영리한 아이디어가지고 imagecolorat()있습니다. 하지만 이로 인해 서버 측에 액세스 할 수있는 이미지로 범위가 제한되며 범용 도구를 정말로 꿈꾸고 있습니다.

이러한 접근 방식 중 하나로 작업 할 것이지만 서버 측 조작 및 확장 설치가 필요없는 크로스 브라우저, 자바 스크립트 또는 플래시 기반 방식을 훨씬 선호합니다.

또한 ColorZilla가 할 수있는 작업을 수행하는 모든 IE 특정 솔루션에 관심이 있습니다. 물론 크로스 브라우저 솔루션이 이상적이지만 IE 및 FF 만 지원하면서 살 수 있습니다.


교차 도메인 보안에 위배되므로 JavaScript로는 불가능합니다. 이미지를 구성하는 픽셀을 알고 있다면 매우 나쁠 것 http://some-other-host/yourPassword.png입니다. 마우스가 캔버스 위에 있거나 동일한 도메인의 이미지 요소 (또는 Access-Control-Allow-Origin: *헤더 와 함께 제공되는 다른 도메인의 이미지 요소) 위에있는 경우에만 마우스 아래의 픽셀 색상을 알 수 있습니다 . 캔버스의 경우 canvasElement.getContext('2d').getImageData(x, y, 1, 1).data. 이미지의 경우 다음을 사용하여 캔버스에 그려야합니다.

var canvas = document.createElement("canvas");
canvas.width = yourImageElement.width;
canvas.height = yourImageElement.height;
canvas.getContext('2d').drawImage(yourImageElement, 0, 0);

그런 다음 캔버스에 대해 설명한 이전 방법을 사용하십시오. 색상 값의 다양한 표현으로 변환 할 수 있어야한다면 내 color.js 라이브러리를 사용 해보세요 .

또한 IE <9 (IE9가 캔버스를 지원한다고 가정)를 지원할 수 없으며 문서의 픽셀 데이터를 읽을 수 없기 때문에 Flash를 사용하는 것도 도움이되지 않습니다.


Browser Timing Attack 이라는 기술을 사용하면 iframe에서도 모든 픽셀의 색상을 결정할 수 있습니다.

기본적으로이 기술은 색상 자체가 아닌 요소에서 SVG 필터를 렌더링하는 requestAnimationFrame()시간을 측정 합니다 ( 보다 훨씬 더 정확하게 시간을 측정 할 수 있습니다 setTimeout()). 현재 픽셀 색상에 따라 필터를 적용하는 데 다소 시간이 걸립니다. 이렇게하면 픽셀이 알려진 색상 (예 : 검정색 또는 흰색)과 동일한 색상인지 확인할 수 있습니다.

이 백서 (pdf)의 자세한 내용 : http://www.contextis.com/documents/2/Browser_Timing_Attacks.pdf

그건 그렇고 : 예, 이것은 브라우저 보안 허점이지만 브라우저 공급 업체가 어떻게 패치 할 수 있는지 모르겠습니다.


여기 StackOverflow와 다른 사이트에서 발견 된 다양한 참조를 병합하여 javascript와 JQuery를 사용했습니다.

<html>
<body>
<canvas id="myCanvas" width="400" height="400" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script src="jquery.js"></script>
<script type="text/javascript">
    window.onload = function(){
        var canvas = document.getElementById('myCanvas');
        var context = canvas.getContext('2d');
        var img = new Image();
        img.src = 'photo_apple.jpg';
        context.drawImage(img, 0, 0);
    };

    function findPos(obj){
    var current_left = 0, current_top = 0;
    if (obj.offsetParent){
        do{
            current_left += obj.offsetLeft;
            current_top += obj.offsetTop;
        }while(obj = obj.offsetParent);
        return {x: current_left, y: current_top};
    }
    return undefined;
    }

    function rgbToHex(r, g, b){
    if (r > 255 || g > 255 || b > 255)
        throw "Invalid color component";
    return ((r << 16) | (g << 8) | b).toString(16);
    }

$('#myCanvas').click(function(e){
    var position = findPos(this);
    var x = e.pageX - position.x;
    var y = e.pageY - position.y;
    var coordinate = "x=" + x + ", y=" + y;
    var canvas = this.getContext('2d');
    var p = canvas.getImageData(x, y, 1, 1).data;
    var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
    alert("HEX: " + hex);
});
</script>
<img src="photo_apple.jpg"/>
</body>
</html>

이것이 나의 완전한 해결책입니다 .. 여기에서는 캔버스와 하나의 이미지 만 사용했지만 <map>이미지 위에 사용해야 하는 경우에도 가능합니다. 도움이 되었기를 바랍니다.


나는 엘리야가 제공 한 매우 상세한 답변에 동의합니다. 또한 이미지에 관해서는 캔버스가 필요하지 않다고 말하고 싶습니다. 자신이 말했듯이 PHP 내에서 해당 이미지를 사용할 수 있으며 서버에서 색상 쿼리를 수행 할 수 있습니다.

I would suggest that you handle this problem with an external tool - this makes it even browser indepedent (but OS dependent): write a small tool (for instance in c#) which does the color query for you, is invoked with a shortcut and submits the color to your server. Make the tool available as download on your CMS.

Another aproach I used for a CMS was to "steal" colors by parsing the CSS: the use case was to make the colors of an already existing web site available as color palette to my application:

  • I asked the user to provide a URL from the target system - mostly the company's home page
  • I parsed the page to find all color definitions in all inline styles and linked styles
  • (you can easily extend this to all referenced images)
  • the result was a nice color palette with all coporate colors to choose from

Maybe that's also a solution for your CMS?


I don't know if this is feasible, but if your pages are static you could save an image screenshot of each one of them (or maybe one for each browser/screen resolution? ) and then use AJAX to send the cursor coordinates to the server and return the pixel color with PHP's imagecolorat().

To take the screenshots, you could use Selenium IDE like described here.

Hope it helps.


See new input[type=color] HTML5 element: http://www.w3.org/TR/html-markup/input.color.html, http://demo.hongkiat.com/html5-form-input-type/index2.html.

Now it works at least in Chrome (tested in Ubuntu, should work for Windows too). It launches color-select dialog provided by operating system. If there is an eyedropper in this dialog (it is for Gnome), then it's possible to pick a color from any point on your screen. Not cross-browser yet, but clean and standards-based.


To add to the previous answers --

One way of thinking of this problem is that you want to be able to do a screen-capture of a 1px by 1px region. A fairly common technique for capturing screen regions (for instance from within Web-based bug-reporting systems) is to use a signed Java applet and java.awt.Robot to capture the picture. If you sign the applet, your users will get a "do you trust this app" dialog (with an "always trust apps from this publisher" checkbox) and then will be able to use the tool.

You can then pass the result out to JavaScript using LiveConnect (the docs are old, but Java applets still support this), or you can post it to your server. Similarly, you can call into the Java applet from JavaScript.


As a security precaution you can't capture screen pixels with Javascript (so developers can't take snapshots of your personal data), but you CAN do it in Flash -- you can get pixel data within the Flash container using the flash.display.BitmapData class.

Check out http://www.sephiroth.it/tutorials/flashPHP/print_screen/ -- I've used it in Flash-based WYSYWIG projects to save images to a LAMP (PHP) server.

The problem with using Flash is that it's not natively supported on iOS devices, which are extremely popular now and worth developing for. Flash is on its way down the tubes.

The canvas-based method will certainly be a good one provided all of your visitors have up-to-date web browsers that support the canvas tag and JavaScript.


There is no built in DOM method to generically get the color of a DOM element (other than images or a <canvas>) at a particular pixel location.

Thus, in order to do this, we must use something like HTML2Canvas or DOM Panda to take a "screenshot" of our website, get the user's click location, and get the pixel color of the "screenshot" at that particular location.

Using HTML2Canvas (version 0.5.0-beta3) you can do something like this:

// Take "screenshot" using HTML2Canvas
var screenshotCanvas,
    screenshotCtx,
    timeBetweenRuns = 10,
    lastTime = Date.now();
function getScreenshot() {
    // Limit how soon this can be ran again
    var currTime = Date.now();
    if(currTime - lastTime > timeBetweenRuns) {
        html2canvas(document.body).then(function(canvas) {
            screenshotCanvas = canvas;
            screenshotCtx = screenshotCanvas.getContext('2d');
        });
        lastTime = currTime;
    }
}
setTimeout(function() { // Assure the initial capture is done
    getScreenshot();
}, 100);

// Get the user's click location
document.onclick = function(event) {
    var x = event.pageX,
        y = event.pageY;

    // Look what color the pixel at the screenshot is
    console.log(screenshotCtx.getImageData(x, y, 1, 1).data);
}


// Update the screenshot when the window changes size
window.onresize = getScreenshot;

Demo

참고URL : https://stackoverflow.com/questions/1936021/javascript-eyedropper-tell-color-of-pixel-under-mouse-cursor

반응형