實現目標:在畫布上嵌入一個圖片,鼠標在圖像上移動的時候顯示鼠標所在位置顏色信息html
實現方法:jquery
(1)建立一個圖片對象canvas
(2)圖片對象加載完成時,執行獲取顏色信息的函數跨域
(3)顏色信息的函數主要包括,獲取鼠標所在點的位置,經過getImageData獲取鼠標所在點的像素對象,並最終得到rgba信息app
(4)爲canvas註冊 mousemove 事件函數
<body > <canvas id="canvas" width="647" height="520" style=""></canvas> <div id="color">鼠標浮到圖片上移動顯示選擇的顏色</div> <script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script> <script> var img = new Image(); img.src = 'images/rhino.jpg'; var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); img.onload = function() { ctx.drawImage(img,0,0); img.style.display="none" }; var color = document.getElementById("color"); function pick(event) { var x = event.layerX; var y = event.layerY; var pixel = ctx.getImageData(x,y,1,1); var data = pixel.data; var rgba = 'rgba('+data[0]+','+data[1]+','+data[2]+','+data[3]/255+')'; color.style.background = rgba; color.style.color = "#fff"; color.innerText = rgba } canvas.addEventListener("mousemove",pick) </script> </body>
查看選擇器效果code
注意:htm
(1)圖片的路徑不能跨域,不然getImageData不執行,會報錯顯示Uncaught DOMException: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.對象
(2)要發佈後才能正常顯示事件