从HTML画布中获取Pixel?

从HTML画布中获取Pixel

是否可以查询HTML画布对象以获得特定位置的颜色?



慕雪6442864
浏览 545回答 3
3回答

慕田峪7331174

有一节是关于像素操纵在W3C文档中。这是关于如何倒置图像的一个例子://&nbsp;Get&nbsp;the&nbsp;CanvasPixelArray&nbsp;from&nbsp;the&nbsp;given&nbsp;coordinates&nbsp;and&nbsp;dimensions.var&nbsp;imgd&nbsp;=&nbsp;context.getImageData(x,&nbsp;y,&nbsp;width,&nbsp;height); var&nbsp;pix&nbsp;=&nbsp;imgd.data;//&nbsp;Loop&nbsp;over&nbsp;each&nbsp;pixel&nbsp;and&nbsp;invert&nbsp;the&nbsp;color.for&nbsp;(var&nbsp;i&nbsp;=&nbsp;0,&nbsp;n&nbsp;=&nbsp;pix.length;&nbsp;i&nbsp;<&nbsp;n;&nbsp;i&nbsp;+=&nbsp;4)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;pix[i&nbsp;&nbsp;]&nbsp;=&nbsp;255&nbsp;-&nbsp;pix[i&nbsp;&nbsp;];&nbsp;//&nbsp;red &nbsp;&nbsp;&nbsp;&nbsp;pix[i+1]&nbsp;=&nbsp;255&nbsp;-&nbsp;pix[i+1];&nbsp;//&nbsp;green &nbsp;&nbsp;&nbsp;&nbsp;pix[i+2]&nbsp;=&nbsp;255&nbsp;-&nbsp;pix[i+2];&nbsp;//&nbsp;blue &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;i+3&nbsp;is&nbsp;alpha&nbsp;(the&nbsp;fourth&nbsp;element)}//&nbsp;Draw&nbsp;the&nbsp;ImageData&nbsp;at&nbsp;the&nbsp;given&nbsp;(x,y)&nbsp;coordinates.context.putImageData(imgd,&nbsp;x,&nbsp;y);

繁星点点滴滴

您试过getImageData方法吗?var&nbsp;data&nbsp;=&nbsp;context.getImageData(x,&nbsp;y,&nbsp;1,&nbsp;1).data;var&nbsp;rgb&nbsp;=&nbsp;[&nbsp;data[0],&nbsp;data[1],&nbsp;data[2]&nbsp;];

繁华开满天机

是的,当然,只要你有它的背景。如何获得画布上下文?var&nbsp;imgData&nbsp;=&nbsp;context.getImageData(0,0,canvas.width,canvas.height);//&nbsp;{&nbsp;data:&nbsp;[r,g,b,a,r,g,b,a,r,g,..],&nbsp;...&nbsp;}function&nbsp;getPixel(imgData,&nbsp;index)&nbsp;{ &nbsp;&nbsp;var&nbsp;i&nbsp;=&nbsp;index*4,&nbsp;d&nbsp;=&nbsp;imgData.data; &nbsp;&nbsp;return&nbsp;[d[i],d[i+1],d[i+2],d[i+3]]&nbsp;//&nbsp;returns&nbsp;array&nbsp;[R,G,B,A]}//&nbsp;AND/ORfunction&nbsp;getPixelXY(imgData,&nbsp;x,&nbsp;y)&nbsp;{ &nbsp;&nbsp;return&nbsp;getPixel(imgData,&nbsp;y*imgData.width+x);}
打开App,查看更多内容
随时随地看视频慕课网APP