好的,我对https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/getImageData的get Image Data函数感到困惑
我有一个png格式的路径图像,上面有透明背景。我需要获取的是高度为2时路径的左边缘和右边缘的坐标x,y。(红色箭头的要点)
getImageData是正确使用的函数吗?任何人都可以就如何获得建议提供一些建议吗?
提前致谢。
是的,getImageData(x, y, width, height);
如果您只有两种颜色(此处为透明和白色),请使用:
var img = new Image();
img.onload = getPoints;
img.crossOrigin = 'anonymous';
img.src = "https://dl.dropboxusercontent.com/s/lvgvekzkyqkypos/path.png";
function getPoints(){
// set our canvas
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
canvas.width = this.width;
canvas.height = this.height;
// draw the image
ctx.drawImage(this,0,0);
// get the middle y line
var imageData = ctx.getImageData(0,Math.floor(this.height/2), this.width, 1);
var data = imageData.data;
// set an empty object that will store our points
var pts = {x1: null, y1: Math.floor(this.height/2), x2: null, y2:Math.floor(this.height/2)};
// define the first opacity value
var color = 0;
// iterate through the dataArray
for(var i=0; i<data.length; i+=4){
// since we'relooking only for non-transparent pixels, we can check only for the 4th value of each pixel
if(data[i+3]!==color){
// set our value to this new one
color = data[i+3];
if(!pts.x1)
pts.x1 = i/4;
else
pts.x2 = i/4;
}
}
snippet.log('start points : '+pts.x1+'|'+pts.y1);
snippet.log('end points : '+pts.x2+'|'+pts.y2);
ctx.fillStyle = 'red';
ctx.fillRect(pts.x1-5, pts.y1, 10, 10);
ctx.fillRect(pts.x2-5, pts.y2, 10, 10);
document.body.appendChild(canvas);
}
body{background-color: blue}
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句