我的HTML代码中有一个图片代码,src
包含本地图片的路径。
<img alt="abc" src="./images/abc.png" />
单击图像后,我想调用一个JavaScript方法,该方法将返回图像的缓冲区数据。
缓冲区示例:
(23234)[234,345,786]
如何在纯JavaScript中完成?
答案 0 :(得分:0)
您无法从图像中读取像素,但可以将图像绘制到画布上,并使用getImageData
提取RGBA像素数据的数组。然后可以在鼠标光标下获得颜色
关于以下示例的说明:
getImageData
具有跨源保护,并且因为上传图像似乎不可能,所以图像以数据URI编码<img src="something.jpg" ...
(所以在本地托管),它可以是一个大图像,它也适用于IE < / LI>
imgready
函数的消息,因此StackOverflow可能会先加载HTML并稍后注入脚本。如果您看到该消息,请再次运行该代码段。随着更多&#34;传统&#34;代码顺序(位于head
中的脚本)不可能发生
var imgdata;
function imgready(){
var img=document.getElementById("you");
var cnv=document.createElement("canvas");
var w=cnv.width=img.width;
var h=cnv.height=img.height;
var ctx=cnv.getContext("2d");
ctx.drawImage(img,0,0);
imgdata=ctx.getImageData(0,0,w,h);
}
function mmove(event){
if(!imgdata)return;
var x=event.clientX-event.target.offsetLeft;
var y=event.clientY-event.target.offsetTop;
var offset=(x+y*imgdata.width)*4;
var r=imgdata.data[offset];
var g=imgdata.data[offset+1];
var b=imgdata.data[offset+2];
document.getElementById("logdiv").innerText=x+","+y+" ("+offset+"): r="+r+" g="+g+" b="+b;
var cnv=document.getElementById("colorcnv");
var ctx=cnv.getContext("2d");
ctx.clearRect(0,0,cnv.width,cnv.height);
ctx.fillStyle="rgb("+r+","+g+","+b+")";
ctx.beginPath();
ctx.arc(10,10,10,0,Math.PI*2);
ctx.fill();
}
&#13;
<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/4QAqRXhpZgAASUkqAAgAAAABADEBAgAHAAAAGgAAAAAAAABHb29nbGUAAP/bAIQAAwICAwICAwMDAwQDAwQFCAUFBAQFCgcHBggMCgwMCwoLCw0OEhANDhEOCwsQFhARExQVFRUMDxcYFhQYEhQVFAEDBAQFBAUJBQUJFA0LDRQUFBQUExQPFBQUFBQUFBQUFBQUFBQUEBUUFBQVDxQUFA4UFBQVFBEVFBQTFBQUERQU/8AAEQgAFAAUAwERAAIRAQMRAf/EABoAAAEFAQAAAAAAAAAAAAAAAAgEBQYHCQP/xAAnEAABAwMEAQMFAAAAAAAAAAABAgMFBBEhAAYHEmETIjEII0FCof/EABkBAAIDAQAAAAAAAAAAAAAAAAQGAwUHAv/EACwRAAEDAwIDBgcAAAAAAAAAAAECAxEABCExUQUGEkFhweHw8RMiMnGBsdH/2gAMAwEAAhEDEQA/AM6GuRZOaplxjVGyh2oQWkuNEhQxm3m2NVhtUNHrJwKPDql/KBVkO/SDPDa9DKRM9QyMm+EOCLbSUOtNFQBeKrmyR83tnqbXItpbb5nZLpbeaKUyROudojt98VZq4QtKAptYJ1inWqjEsVC2i428WyUF1o3Qu2OyTYYPyNGJV1CRiuYjFRSf4KmuERszcM49RvOzdIJOgj2qhtai0W0KBc6LUW7esgWUkEnsAD1JDOi3evVFgCJ7Z8KqSWmEhwKk7R40SXB3M8NOcPbm2puGoVB1VLQ1b7zTTQSiqZKlOKSwv9VdlC4JTg4CsqTn/HuWb3h9wi4t09SCpIB1IOAOoffAORvGlMVpxVm5a+C4YUAZ79Tj1/aGyOl9xGjbK32XV2ytbIyfFrY8/nW0K5aszmFD8+RpUTfORSrdG5ZvccjGtzM7LTbVBQKYo25Svdq00rVh9toOKV6aPan2psMDGg+GmHFK2FDOfTXCnYQaZN09u1yQrOQQR/dPgSClJ7/36mgN6WvrU2vrcqsPk6kccKVECpUiRX//2Q==" id="you" onload="imgready()" onmousemove="mmove(event)">
<canvas id="colorcnv" width="20" height="20"></canvas><br>
<div id="logdiv"></div>
&#13;