在按钮单击上绘制多行JavaScript - 不使用画布

时间:2018-06-18 13:57:38

标签: javascript jquery html css3 canvas

我想知道是否可以像这个Fiddle项目一样获得多个绘图线 -

然而,如果不使用canvas,而是使用带有css背景图像的普通div框?

使用画布下面的代码

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

var line, isDown;

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

canvas.on('mouse:move', function(o){
  if (!isDown) return;
  var pointer = canvas.getPointer(o.e);
  line.set({ x2: pointer.x, y2: pointer.y });
  canvas.renderAll();
});

canvas.on('mouse:up', function(o){
  isDown = false;
});

由于

1 个答案:

答案 0 :(得分:1)

我对示例进行了一些修正,以便向所有方向绘制,而这仅适用于css3:

请注意,您必须定义指向(两次点击)以绘制线条。

见下面的代码:

$(function() {
  var x1 = null,
    y1 = null;
  var offsetX = 0,
    offsetY = 0;

  function createLine(x1, y1, x2, y2) {

    var length = Math.sqrt(((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2)));
    var angle = Math.atan2(y2 - y1, x2 - x1) * 180 / Math.PI;
    var transform = 'rotate(' + angle + 'deg)';

    offsetX = (x1 > x2) ? x2 : x1;
    offsetY = (y1 > y2) ? y2 : y1;

    var line = $('<div>')
      .appendTo('#demo')
      .addClass('line')
      .css({
        'position': 'absolute',
        '-webkit-transform': transform,
        '-moz-transform': transform,
        'transform': transform
      })
      .width(length)
      .offset({
        left: offsetX,
        top: offsetY
      });

    return line;
  }

  $('#demo').click(function(event) {
      var x = event.pageX,
        y = event.pageY;

      if (x1 == null) {
        x1 = x;
        y1 = y;
      } else {
        createLine(x1, y1, x, y);
        x1 = y1 = null;
      }
    })
    .delegate('.line', 'click', function(event) {
      event.preventDefault();
      $(this).toggleClass('active');
      x1 = y1 = null;
      return false;
    });





});
div.line {
  transform-origin: 0 100%;
  height: 3px;
  /* Line width of 3 */
  background: #000;
  /* Black fill */
}

#demo {
  border: 1px dashed #ccc;
  height: 400px;
}

div.transforming-on-corner {
  transform-origin: 0% 0%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h3> click two point to draw a line :</h3>
<div id="demo" class="wide">

</div>