对于某个图像,我有一个列表,其中包含一个多边形中所有点的像素坐标,该多边形分割了它包含的所有对象(请看下图)。
例如,对于人,我有一个列表 l1 = [x0,y0,x1,y1,...,xn,yn]
,对于猫,我有一个列表 l2 = [x0',y0',x1',y1',...,xk',yk']
,对于所有对象也是如此。
我有两个问题:
用于在图像上绘图的最佳
javascript
库是什么?鉴于原始图像,我想获得如下所示的结果。我希望每个分段仅在鼠标悬停在其上时才可视化。为此,我认为我应该将此绘图函数绑定(bind)到鼠标位置。
我正在考虑以下结构的东西,但不知道如何填补空白,你能给我一些指示吗?
$(.container).hover( function(e) {
//get coordinates of mouse
//if mouse is over one object
//draw on top of image the segmentation for that object
});
container
是包含图像的 div 的类,因此我应该能够获取鼠标的坐标,因为图像从 container
的左上角开始> 分区。
最佳答案
只需从每个数组重建多边形并使用鼠标位置进行 HitTest 。
首先:如果您有许多定义形状的数组,那么以更通用的方式处理它可能更明智,而不是为每个数组使用变量,因为这很快就会难以维护。更好的是,一个包含数组的对象,例如 id 可能会更好。
使用您可以做的对象 - 示例:
function Shape(id, points, color) {
this.id = id;
this.points = points;
this.color = color;
}
// this will build the path for this shape and do hit-testing:
Shape.prototype.hitTest = function(ctx, x, y) {
ctx.beginPath();
// start point
ctx.moveTo(this.points[0], this.points[1]);
// build path
for(var i = 2, l = this.points.length; i < l; i += 2) {
ctx.lineTo(this.points[i], this.points[i+1]);
}
ctx.closePath();
return ctx.isPointInPath(x, y);
};
现在您可以像这样使用各种点数组创建新实例:
var shapes = [];
shapes.push(new Shape("Cat", [x0,y0,x1,y1, ...], "rgba(255,0,0,0.5)");
shapes.push(new Shape("Woman", [x0,y0,x1,y1, ...], "rgba(0,255,0,0.5)"));
...
当您获得鼠标位置时,只需点击测试每个形状:
$(".container").hover( function(e) {
//get corrected coordinates of mouse to x/y
// redraw canvas without shapes highlighted
for(var i = 0, shape; shape = shapes[i]; i++) { // get a shape from array
if (shape.hitTest(ctx, x, y)) { // is x/y inside shape?
ctx.fillStyle = shape.color; // we already have a path
ctx.fill(); // when testing so just fill
// other tasks here...
break;
}
}
});
关于javascript - 使用javascript在图像上绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26984834/