如何使用JavaScript获取html中图片的像素值
原理就是借助canvas对象,首先获取图片的img标签对象,然后通过canvas load这个对象,最后通过canvas的api获得像素和通道信息
代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta content="text/html;charset=utf-8" http-equiv="Content-Type"> <title> javascript get pixel </title> </meta> <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script> </head> <body> <img src="../demo/wall/texture3.jpg" alt="" id="testimg"/> <script type="text/javascript"> $(function(){ function getPixel(image, x, y) { var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); context.drawImage(image, 0, 0); return context.getImageData(x, y, 1, 1).data; } console.log(getPixel(document.getElementById("testimg"), 100, 10)); }); </script> </body> </html>