Я рисую линию, используя SVG и jQuery UI. Я хочу нарисовать ее во всех направлениях, но она не работает. - PullRequest
0 голосов
/ 19 декабря 2018

перетаскиваемый и изменяемый размер кода находится внутри этой функции

makeDragableLine('#maindiv #annotationText',jQuery('#maindiv'));

HTML / SVG часть кода ниже: -

<div id="maindiv">
    <div id="annotationText">
    <svg id="line" height="210" width="500">
      <line x1="0" y1="0" x2="200" y2="200" style="stroke:rgb(255,0,0);stroke-width:2" />
    </svg>
    </div>
    </div>

ниже находится основная функция

function makeDragableLine(selector,obj){

    var height=obj.height();
        var width=obj.width();
        var objdiv = $(selector);
        var line = $("#line", objdiv);
        var objdiv=jQuery( selector );
          jQuery( selector ).draggable({      
              containment: obj,
              drag: function( event, ui ) { 
              var cleft=ui.position.left*100/width;
              var top=ui.position.top*100/height;
              jQuery(event.target).attr('data-offsetx',cleft);
              jQuery(event.target).attr('data-offsety',top);

              }, stop: function( event, ui ) {
                console.log('doneDrag1');
                var PageNumber=jQuery(event.target).parents('.page').attr('data-page-number');
                    var parentele=jQuery(event.target)
                  SaveAnnotation(parentele,PageNumber);

               }

          }).resizable({
          //aspectRatio: 1.0,
          handles: 'ne, se, sw, nw',
          containment: obj,
          minWidth: 40,
          minHeight: 40,
          resize: function(e, ui) {
            line.attr({
              width: ui.size.width,
              height: ui.size.height
            });
            $("line", line).attr({
              x1: ui.size.width,
              y1: ui.size.height,
              x2: e.offsetX,
              y2: e.offsetY
            });
          }
        });

    }

Как правильно нарисовать линию, используя SVG?Я могу это сделать, но это не так, как я хочу.линия, которую я рисую в приведенном выше коде, не следует за изменяемым указателем во всех направлениях.

1 Ответ

0 голосов
/ 19 декабря 2018

const SVG_NS = "http://www.w3.org/2000/svg";
let svg = document.querySelector("#lines");
let m = {};// the mouse position
let oLine = {};// an object for the line's attributes
let eLine = null; //the line element

//events
// on mouse down you create the line and append it to the svg element
lines.addEventListener("mousedown", e => {
  m = oMousePosSVG(e);
  oLine.x1 = m.x;
  oLine.y1 = m.y;
  oLine.x2 = m.x;
  oLine.y2 = m.y;
  eLine = drawline(oLine, lines);
});
// on mouse move you update the line 
lines.addEventListener("mousemove", e => {
  if (eLine) {
    m = oMousePosSVG(e);
    oLine.x2 = m.x;
    oLine.y2 = m.y;
    updateLine(oLine, eLine);
  }
});
// on mouse up or mouse out the line ends here and you "empty" the eLine and oLine to be able to draw a new line
lines.addEventListener("mouseup", e => {
  if (eLine) {
    m = oMousePosSVG(e);
    eLine = null;
    oLine = {};
  }
});

lines.addEventListener("mouseout", e => {
  if (eLine) {
    m = oMousePosSVG(e);
    eLine = null;
    oLine = {};
  }
});


// a function to draw a line in SVG
function drawline(o, parent) {
  let line = document.createElementNS(SVG_NS, "line");
  for (var name in o) {
    if (o.hasOwnProperty(name)) {
      line.setAttributeNS(null, name, o[name]);
    }
  }
  parent.appendChild(line);
  return line;
}
// a function to update a line in SVG
function updateLine(o, element) {
  for (var name in o) {
    if (o.hasOwnProperty(name)) {
      element.setAttributeNS(null, name, o[name]);
    }
  }
  return element;
}
// a function to detect the mouse position on a resizable SVG element
function oMousePosSVG(ev) {
  var p = svg.createSVGPoint();
  p.x = ev.clientX;
  p.y = ev.clientY;
  var ctm = svg.getScreenCTM().inverse();
  var p = p.matrixTransform(ctm);
  return p;
}
svg{border:1px solid;}
line{stroke:rgb(255,0,0);stroke-width:2;pointer-events:none;}
<div id="maindiv">
    <div id="annotationText">
    <svg id="lines" height="210" width="500">
      <line x1="0" y1="0" x2="200" y2="200" />
    </svg>
    </div>
    </div>

Наблюдение : если вам нужен отзывчивый SVG, пожалуйста, измените атрибуты ширины и высоты для viewBox в этом случаеviewBox="0 0 210 500"

Если вам нужно сохранить строки для последующего повторного использования, вы можете вставить eLine в массив при наведении курсора мыши и отпускании мыши.

...