按扣织物。线条为45度角

时间:2016-03-29 04:09:30

标签: fabricjs

我正在尝试在fabricJS中使用fabric.Line(),这样当用户开始绘制一条线时,它会从起始点以45度角捕捉到八个角度中的一个角度。这与使用Adobe产品时按住班次类似。这可能与fabricJS有关吗?

1 个答案:

答案 0 :(得分:0)

好的,我们知道行起始X1和Y1以及行结束X2和Y2点。我们也知道45度的角度。

所以在这里我们应用一些数学来获得输出。

在X1和Y1点停留在那里,X2和Y2点想要以45度角行进。

X2 = Math.cos(angle * Math.PI/180) * distence + startX Y2 = Math.sin(angle * Math.PI/180) * distence + startY tanks for this

这里

startX = x1
startY = y1 
angle=45
distence = current.mouse.x-x1

所以我们可以得到角度为45度的x2,y2

让我们在fabricjs

上试试

var canvas = new fabric.Canvas('c', {
  selection: false
});

var line, isDown, points;

canvas.on('mouse:down', function(o) {
  isDown = true;
  var pointer = canvas.getPointer(o.e);
  points = [pointer.x, pointer.y, pointer.x, pointer.y];
  line = new fabric.Line(points, {
    strokeWidth: 2,
    fill: 'red',
    stroke: 'red',
    originX: 'left',
    originY: 'center'

  });
  canvas.add(line);
});

canvas.on('mouse:move', function(o) {
  if (!isDown) return;
  var pointer = canvas.getPointer(o.e);

  var startX = points[0];
  var startY = points[1];
  var distence = pointer.x - points[0];
  var angle = -45

  x2 = Math.round(Math.cos(angle * Math.PI / 180) * distence + startX);
  y2 = Math.round(Math.sin(angle * Math.PI / 180) * distence + startY);
  console.log("x2 >>> " + x2 + " y2 >>>>> " + y2)

  line.set({
    x2: x2,
    y2: y2
  });
  canvas.renderAll();
});

canvas.on('mouse:up', function(o) {
  isDown = false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>

<canvas id="c" width="300" height="200"></canvas>