FabricJS圆圈显示半径

时间:2016-10-21 12:46:58

标签: javascript canvas fabricjs

我在项目中使用了fabricjs,但我想在结构上显示圆的半径。我可以问一下如何做到这一点。最多可能有20个圆圈,我需要这些信息,圆圈将有控件,因此可以通过调整半径文本进行扩展以进行补偿。

http://jsfiddle.net/wayneker/a3q5c40r/

var canvas = new fabric.Canvas('canvas');

var circle = new fabric.Circle({
    left: 50,
    top: 50,
    fill: "",
    radius: 40,
    hasControls: false, 
    hasRoatatingPoint: false,
    stroke: 'red',
    strokeWidth: 1  

});

canvas.add(circle); 

如果这不可能,用户可以通过输入设置半径吗?

1 个答案:

答案 0 :(得分:2)

我不确定你要做什么。在下面的示例中,我有一个按钮,可以将一个组广告到圆形和文本框的画布上。选择其中一个组时,会出现一个范围输入,允许您更改半径。在改变时,我们到达小组并更新圆圈的文本和半径。

window.canvas = new fabric.Canvas('canvas');

function getCircleGroup(radius = 40) {
  var text = new fabric.Text(radius.toString(), {
      left: 50,
      top: 50,
  });
  var circle = new fabric.Circle({
      left: 50,
      top: 50,
      fill: "",
      radius: radius,
      hasControls: false, 
      hasRoatatingPoint: false,
      stroke: 'red',
      strokeWidth: 1  

  });
  
  return new fabric.Group([ circle, text ], {
  	    lockScalingX: true,
  	    lockScalingY: true,
  });

}

var button = document.querySelector('button');
button.addEventListener('click', () => {
  var group = getCircleGroup();
  canvas.add(group);
  canvas.setActiveObject(group);
  canvas.renderAll();
});

canvas.on('object:selected', (o) => {
  var r = document.querySelector('.radiusChange');
  r.style.display = 'block';
  r.querySelector('input').value = o.radius;
})

canvas.on('selection:cleared', () => {
	var r = document.querySelector('.radiusChange');
	r.style.display = 'none';
});

var radiusChanger = document.querySelector('.radiusChange input')
radiusChanger.addEventListener('change', (e) => {
  var group = canvas.getActiveObject();
  var top = group.top;
  var left = group.left;
  group.item(0).setRadius(parseInt(e.target.value));
  group.item(1).text = e.target.value;
  group._calcBounds();
  group._updateObjectsCoords();
  group.top = top;
  group.left = left;
  canvas.renderAll();
})
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.6/fabric.min.js"></script>
<button>add circle</button>
<div class="radiusChange" style="display:none;">
<br />change radius: <input type="range" max=100 min=10 step=1 /></div>
<canvas id="canvas" width="300" height="300" style="border:1px solid;"></canvas>