2015-02-11 71 views
1

我想使用fabricjs創建一個對象,並可以測量一些圖像部分。fabricjs我如何做角度測量?

更新:

我遵循的http://fabricjs.com/stickman/樣本,看來我的東西,但需要提高更多的

這裏是我有https://jsfiddle.net/mavirroco/gtfw58st/

(function() { 
var canvas = this.__canvas = new fabric.Canvas('c', { 
    selection: false 
}); 
var text1 = new fabric.Text('0 Deg', { 
    fontSize: 20, 
    fontFamily: 'Georgia', 
    top: 10, 
    left: 100 
}); 
canvas.add(text1); 

fabric.Object.prototype.originX = fabric.Object.prototype.originY = 'center'; 

function makeCircle(left, top, line1, line2, line3, line4) { 
    var c = new fabric.Triangle({ 
     left: left, 
     top: top, 
     strokeWidth: 5, 
     fill: '#fff', 
     stroke: '#666', 
     angle: -180, 
     width: 10, 
     height: 10 
    }); 
    c.hasControls = c.hasBorders = false; 

    c.line1 = line1; 
    c.line2 = line2; 
    c.line3 = line3; 
    c.line4 = line4; 

    return c; 
} 

function makeLine(coords) { 
    return new fabric.Line(coords, { 
     fill: 'red', 
     stroke: 'red', 
     strokeWidth: 5, 
     selectable: false 
    }); 
} 

var line2 = makeLine([250, 175, 250, 250]), 
    line3 = makeLine([250, 250, 300, 350]), 
    line4 = makeLine([250, 250, 200, 350]); 


canvas.add(line3, line4); 

canvas.add(

makeCircle(line2.get('x2'), line2.get('y2'), line2, line3, line4), 
makeCircle(line3.get('x2'), line3.get('y2'), line3), 
makeCircle(line4.get('x2'), line4.get('y2'), line4)); 

canvas.on('object:moving', function (e) { 
    var p = e.target; 
    p.line1 && p.line1.set({ 
     'x2': p.left, 
      'y2': p.top 
    }); 
    p.line2 && p.line2.set({ 
     'x1': p.left, 
      'y1': p.top 
    }); 
    p.line3 && p.line3.set({ 
     'x1': p.left, 
      'y1': p.top 
    }); 
    p.line4 && p.line4.set({ 
     'x1': p.left, 
      'y1': p.top 
    }); 
    canvas.renderAll(); 

    dy = line3.get('y2') - line4.get('y2'); 
    dx = line3.get('x2') - line4.get('x2'); 
    theta = Math.atan2(dy, dx); 
    theta *= 180/Math.PI // rads to degs 
    text1.setText(parseFloat(theta).toFixed(2)); 
}); 

})();

回答

1
y11 = line3.get('y1'); 
y12 = line3.get('y2'); 
y21 = line4.get('y1'); 
y22 = line4.get('y2'); 

x11 = line3.get('x1'); 
x12 = line3.get('x2'); 
x21 = line4.get('x1'); 
x22 = line4.get('x2'); 

angle1 = Math.atan2(y11 - y12, x11 - x12); 
angle2 = Math.atan2(y21 - y22, x21 - x22); 

angle = angle1 - angle2; 
angle = angle*180/Math.PI; 
if(angle < 0) angle = -angle; 
if(360 - angle < angle) angle = 360 - angle; 
text1.setText(angle.toString()); 

https://jsfiddle.net/gtfw58st/5/

+0

不錯不錯,我會提高更多的把中心三角形內的角度值了一下..我相信的這可以用組..not確保 – mavirroco 2015-02-14 16:17:34

+0

這裏我分享了一個改良效果HTTPS來完成://jsfiddle.net/mavirroco/gtfw58st/7/ – mavirroco 2015-02-14 17:25:01