gpt4 book ai didi

JavaScript Canvas : How to get the specific points on transparent png file?

转载 作者:行者123 更新时间:2023-12-02 15:38:19 25 4
gpt4 key购买 nike

enter image description here

好吧,我对获取图像数据函数感到困惑 https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/getImageData

我有一个 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>

关于JavaScript Canvas : How to get the specific points on transparent png file?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32753830/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com