如何获取画布中绘制对象的位置
我想做的是绘制简单的形状,比如说用鼠标绘制矩形,并直接从画布获取他的坐标、高度和宽度,这可能吗?
我写了这个函数:
function getImageProperties(image){
var xMin = image.width;
var xMax = 0;
var yMin = image.height;
var yMax = 0;
var w = image.width, h = image.height;
for (var y = 0; y < h; y ++) {
for (var x = 0; x < w; x ++) {
for (var c = 1; c < 5; c += 1) {
var i = (x + y * w) + c;
if(image.width* image.height * 4 != i){
if(image.data[i] != 0){
if(x<xMin)
xMin = x;
if(x>xMax)
xMax = x;
if(y<yMin)
yMin = y;
if(y>yMax)
yMax = y;
}
}
}
}
}
var imgProp = {
x : xMin,
y : yMin,
width: (xMax-xMin),
height : (yMax-yMin)
};
return imgProp;
}
但
image = context.getImageData(0, 0, context.canvas.width, context.canvas.height);
返回的数据与我发送到绘图函数的数据不同:/
What i want to do is draw simple shape let's say rectangle by mouse and get directly from canvas his coordinates, height and width, it's possible?
I wrote this function:
function getImageProperties(image){
var xMin = image.width;
var xMax = 0;
var yMin = image.height;
var yMax = 0;
var w = image.width, h = image.height;
for (var y = 0; y < h; y ++) {
for (var x = 0; x < w; x ++) {
for (var c = 1; c < 5; c += 1) {
var i = (x + y * w) + c;
if(image.width* image.height * 4 != i){
if(image.data[i] != 0){
if(x<xMin)
xMin = x;
if(x>xMax)
xMax = x;
if(y<yMin)
yMin = y;
if(y>yMax)
yMax = y;
}
}
}
}
}
var imgProp = {
x : xMin,
y : yMin,
width: (xMax-xMin),
height : (yMax-yMin)
};
return imgProp;
}
where
image = context.getImageData(0, 0, context.canvas.width, context.canvas.height);
but returned data is not same as i send to the drawning function :/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它看起来就像您试图找到包围图像数据中所有非黑色像素的矩形,但如果是这样,我可以看到一些小问题,主要是偏移计算。试试这个:
也就是说,如果您只是用鼠标绘制矩形,那么简单地记录鼠标事件处理程序中使用的最后两对坐标会容易得多!
It looks like you're trying to find the rectangle enclosing all non-black pixels in the image data, but if so I can see a few minor issues, mostly with offset calculations. Try this:
That said, if you just drew the rectangle with a mouse it would be far easier to simply record the last two pairs of coordinates used in your mouse event handlers!
您可以尝试使用 getImageData 读取像素颜色,但这确实不是一个好主意。
最好的方法是将位置和其他数据存储在画布外部的数组中。
You could try reading the pixel colors using
getImageData
, but it really isn't such a good idea.The best approach would be to store the positions and other data in an array outside the canvas.