1

Как реализовать анимацию Drag-and-drop для иконок, а именно сделать движущиеся иконки на странице, но не понимаю как их связать пунктирной линией, которая будет соединять две и более иконки друг с другом и при перемещении их по странице данная пунктирная линия будет растягиваться и уменьшаться между ними, ну и в целом нужно чтобы визуально выглядело все как на скриншоте, какие сторонние библиотеки использовать и как правильней и легче это реализовать?введите сюда описание изображения

1
  • in integromat it was created with canvas with lines, rectangles and gradients, you can create with svg
    – Greg--
    11 окт 2021 в 13:15

3 ответа 3

0

Можно div элементы использовать для кругов, чтобы легче было добавлять различный контент в будущем, а все остальные элементы - линии, соединяющие эти круги и коннекторы рисовать в SVG.

Допустим создаете компонент v-circle. К нему подключаем возможность перемещения этого элемента (я использовал обычные события нажатия и "отжатия" кнопки мыши - это для демонстрации) При перемещении элемента, он отправляет свои обновленные координаты в родительский компонент, где в вычислительном свойстве происходит перерасчет линий, соединяющих круги и других необходимых данных (далее все дело в математике).

Подготовил для вас небольшой пример. По коду вставлены комментарии, чтобы было легче понять, что там происходит.

const appData = {
  setup() {
    const circles = Vue.ref([{
        id: 0,
        x: 50,
        y: 50,
        d: 100,
        color: "#409de4",
        lines: [1, 2], // id окружности(ей), с которой соединена текущая
      },
      {
        id: 1,
        x: 250,
        y: 250,
        d: 100,
        color: "#1a7a3f",
        lines: [3],
      },
      {
        id: 2,
        x: 450,
        y: 30,
        d: 100,
        color: "#35495e",
        lines: [],
      },
      {
        id: 3,
        x: 550,
        y: 200,
        d: 100,
        color: "#f4cd00",
        lines: [0],
      },
    ]);

    /*
     * В вычислительном свойстве, при подготовке линий, соединяющих между собой, указанные выше, точки
     * определяем углы поворотов каждой из этих линий, чтобы узнать координаты
     * точек пересечения линии и окружностей (это нужно чтобы отрисовать окружности - коннекторы)
     *
     */
    const lines = Vue.computed(() => {
      return circles.value.reduce((acc, circleEl) => {
        const lines = circleEl.lines.map((b) => {
          const radius = circleEl.d / 2; // радиус окружности
          const x1 = circleEl.x + radius + 5; // абсцисса начала линии
          const y1 = circleEl.y + radius + 5; // ордината начала линии
          const x2 = circles.value[b].x + circles.value[b].d / 2 + 5; // абсцисса конца линии
          const y2 = circles.value[b].y + circles.value[b].d / 2 + 5; // ордината конца линии

          const calcAngle = (x, y) =>
            x > 0 && y < 0 ?
            Math.PI / 2 + Math.atan(x / y) :
            x <= 0 && y < 0 ?
            Math.PI / 2 + Math.atan(x / y) :
            x > 0 && y >= 0 ?
            (3 * Math.PI) / 2 + Math.abs(Math.atan(x / y)) :
            x <= 0 && y >= 0 ?
            Math.PI + Math.abs(Math.atan(y / x)) :
            0;

          // угол для первой точки
          const ang = calcAngle(x1 - x2, y2 - y1);

          // угол для второй точки
          const ang2 = calcAngle(x2 - x1, y1 - y2);

          return {
            line: {
              x1,
              y1,
              x2,
              y2,
              // stroke: circleEl.color,
            },
            ang,
            ang2,
            colorFrom: circles.value[b].color,
            colorTo: circleEl.color,
            cx: radius * Math.cos(ang) + x2, // абсцисса первой точки
            cy: radius * Math.sin(ang) + y2, // ордината первой точки
            cx2: radius * Math.cos(ang2) + x1, // абсцисса второй точки
            cy2: radius * Math.sin(ang2) + y1, // ордината второй точки
          };
        });
        return acc.concat(lines);
      }, []);
    });

    const addCircle = () => {
      circles.value.push({
        id: circles.value.length,
        x: Math.floor(Math.random() * 500),
        y: Math.floor(Math.random() * 500),
        d: 100,
        color: `#${Math.floor(
                Math.random() * (999999 - 100000) + 100000
              )}`,
        lines: [Math.floor(Math.random() * circles.value.length)],
      });
    };

    return {
      circles,
      lines,
      addCircle,
    };
  },
};

const app = Vue.createApp(appData);

app.component("v-circle", {
  props: ["modelValue"],
  emits: ["update:modelValue"],
  setup(props, {
    emit
  }) {
    // ссылка на элемент, чтобы иметь возможность обращения к нему как к DOM элементу
    const el = Vue.ref(null);

    // флаг перемещения (если он true - меняем координаты текущего элемента)
    const drag = Vue.ref(false);
    // позиция текущего элемента
    const pos = Vue.reactive({
      x: props.modelValue.x,
      y: props.modelValue.y,
    });
    // функция для события перемещения элемента, путем изменения его координат
    const move_handler = (e) => {
      if (drag.value) {
        pos.x = e.pageX - el.value.offsetWidth / 2;
        pos.y = e.pageY - el.value.offsetHeight / 2;
        // передаем измененные координаты в родительский компонент
        emit("update:modelValue", {
          ...props.modelValue,
          x: pos.x,
          y: pos.y,
        });
      }
    };

    const toggleDrag = () => {
      drag.value = !drag.value;
    };

    Vue.onMounted(() => {
      // вешаем обработчик на событие перемещения курсора мыши,
      // чтобы иметь возможность изменить координаты элемента
      window.addEventListener("mousemove", move_handler);
    });

    return {
      el,
      pos,
      drag,
      toggleDrag,
    };
  },
  template: `
      <div ref="el" :class="['circle']" :style="{background: modelValue.color, position:'absolute', top: modelValue.y + 'px', left: modelValue.x + 'px', width: modelValue.d + 'px', height: modelValue.d + 'px'}" @mousedown="toggleDrag" @mouseup="toggleDrag">
          <slot>
        </slot>
      </div>
      `,
});
app.mount("#app");
.circle {
  border-radius: 50%;
  text-align: center;
  cursor: pointer;
  opacity: 1;
  border: 5px solid white;
  color: white;
  font-size: 45px;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  flex-wrap: nowrap;
  justify-content: center;
  user-select: none;
}
<script src="https://unpkg.com/vue@next"></script>
<div id="app">
  <button type="button" @click="addCircle">Add random circle</button>
  <div class="relative">
    <template v-for="(circle,keyCircle) in circles">
          <v-circle v-model="circles[keyCircle]"> {{keyCircle}} </v-circle>

          <template v-if="lines">
            <svg
              style="position: absolute; left: 0; top: 0; z-index: -1"
              width="100vw"
              height="100vh"
            >
              <template v-for="(line, keyLine) in lines">
                <defs>
                  <linearGradient
                    :id="`gr_${keyCircle}_${keyLine}`"
                    v-bind="{...line.line}"
                    gradientUnits="userSpaceOnUse"
                  >
                    <stop :stop-color="line.colorTo" offset="0" />
                    <stop :stop-color="line.colorFrom" offset="1" />
                  </linearGradient>
                </defs>
                <line
                  v-bind="{...line.line}"
                  stroke-width="10px"
                  stroke-linecap="round"
                  stroke-dasharray="1 15"
                  :stroke="`url(#gr_${keyCircle}_${keyLine})`"
                />
                <circle
                  :cx="line.cx"
                  :cy="line.cy"
                  r="15"
                  :fill="line.colorFrom"
                />
                <circle
                  :cx="line.cx2"
                  :cy="line.cy2"
                  r="15"
                  :fill="line.colorTo"
                />
              </template>
    </svg>
    </template>
    </template>
  </div>
</div>

2
  • Спасибо большое, именно то что и нужно было!
    – Roman Ag
    18 окт 2021 в 5:10
  • еще один вопрос, возможно ли ваш код под Vue 2 сделать, очень надо так как с ним не работал и хочется сохранить работоспособность выполнения кода
    – Roman Ag
    5 янв 2022 в 13:38
0

Вот нашел пример Вроде похоже на то, что вы ищете

/*
muConnector - a class to create a line joining two elements.

To use, call new with id's of both elements and optonal lineStyle (which must be a valid css border line def such as '1px solid #000' , e.g.
var c1=new Connector(id1, id2, lineStyle)

Default line style is '1px solid #666666'

Whatever you use for drag control, call moved(e, ele) per increment of movement, where e=event and ele=the jq element being moved.

*/

var Connector = function(params) {
if (typeof(params) == "undefined") { return false }; // If no params then abandon.
// Process input params.
var ele1=params.ele1 || '';   // First element to link
var ele2=params.ele2 || '';   // Second element to link
if ( ele1.length === 0 || ele2.length === 0)  { return false }; // If not two element id's then abandon. 

var className=params.class || 'muConnector'

var lineStyle=params.lineStyle || '1px solid #666666';   // CSS style for connector line.

this.gapX1=params.gapX1 || 0;  // First element gap before start of connector, etc
this.gapY1=params.gapY1 || 0;  
this.gapX2=params.gapX2 || 0;
this.gapY2=params.gapY2 || 0;


this.gap=params.gap || 0; // use a single gap setting.
if ( this.gap > 0 ) {
    this.gapX1 = this.gap
    this.gapY1 = this.gap
    this.gapX2 = this.gap
    this.gapY2 = this.gap
}

var pos = function() { // only used for standalone drag processing.
    this.left = 0;
    this.top = 0;
}
        
this.PseudoGuid = new (function() { // Make a GUID to use in unique id assignment - from and credit to http://stackoverflow.com/questions/226689/unique-element-id-even-if-element-doesnt-have-one
    this.empty = "00000000-0000-0000-0000-000000000000";
    this.GetNew = function() {
        var fC = function() { return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1).toUpperCase(); }
        return (fC() + fC() + "-" + fC() + "-" + fC() + "-" + fC() + "-" + fC() + fC() + fC());
    };
})();

this.id = this.PseudoGuid.GetNew(); // use guid to avoid id-clashes with manual code.
this.ele1=($('#'+ele1));
this.ele2=($('#'+ele2));

// Append the div that is the link line into the DOM
this.lineID='L' + this.id;
$('body').append("<div id='" + this.lineID + "' class='" + className + "' style=  ></div>")
this.line = $('#L'+ this.id);
this.line.css({ position: 'absolute', 'border-left': this.lineStyle, 'z-index': -100 }) 

// We may need to store the offsets of each element that we are connecting.
this.offsets=[];
this.offsets[ele1]=new pos;
this.offsets[ele2]=new pos;

this.link(); // show the initial link
}

/*
Approach: draw a zero width rectangle where the top left is located at the centre of ele1. 
Compute and make rectangle height equal to the distance between centres of ele1 and ele2.
Now rotate the rectangle to the angle between the points.
Note tracks the edges of the elements so as not to overlay / underlay.
Also can accommodate a gap between edge of element and start of line.

*/  
Connector.prototype.link=function link() {

    var originX = this.ele1.offset().left + this.ele1.outerWidth() / 2;
    var originY = this.ele1.offset().top + this.ele1.outerHeight() / 2;
  
    var targetX = this.ele2.offset().left + this.ele2.outerWidth() / 2;
    var targetY = this.ele2.offset().top + this.ele2.outerHeight() / 2;
    
    var l = this.hyp((targetX - originX),(targetY - originY));
    var angle = 180 / 3.1415 * Math.acos((targetY - originY) / l);
    if(targetX > originX) { angle = angle * -1 }
    
    // Compute adjustments to edge of element plus gaps.
    var adj1=this.edgeAdjust(angle, this.gapX1 + this.ele1.width() / 2, this.gapY1 + this.ele1.height() / 2)
    var adj2=this.edgeAdjust(angle, this.gapX2 + this.ele2.width() / 2, this.gapY2 + this.ele2.height() / 2)

 
    l = l - ( adj1.hp + adj2.hp)
    
    this.line.css({ left: originX, height: l, width: 0, top: originY +  adj1.hp })
        .css('-webkit-transform', 'rotate(' + angle + 'deg)')
        .css('-moz-transform', 'rotate(' + angle + 'deg)')
        .css('-o-transform', 'rotate(' + angle + 'deg)')
        .css('-ms-transform', 'rotate(' + angle + 'deg)')
        .css('transform', 'rotate(' + angle + 'deg)')
        .css('transform-origin', '0 ' + ( -1 * adj1.hp) + 'px');

}

Connector.prototype.Round = function(value, places) {
    var multiplier = Math.pow(10, places);
    return (Math.round(value * multiplier) / multiplier);
}
    
Connector.prototype.edgeAdjust = function (a, w1, h1) {
    var w=0, h=0
    
    // compute corner angles
    var ca=[]
    ca[0]=Math.atan(w1/h1) * 180 / 3.1415926 // RADIANS !!!
    ca[1]=180 - ca[0]
    ca[2]=ca[0] + 180
    ca[3]=ca[1] + 180
    
    // Based on the possible sector and angle combinations work out the adjustments.
    if ( (this.Round(a,0) === 0)  ) {
        h=h1
        w=0
    }
    else if ( (this.Round(a,0) === 180)  ) {
        h=h1
        w=0
    }
    else if ( (a > 0 && a <= ca[0]) || (a < 0 && a >= (-1*ca[0]))  ) {
        h=h1
        w=-1 * Math.tan(a * ( 3.1415926 / 180)) * h1
    }
    
    else if (  a > ca[0] && a <= 90 ) {
        h=Math.tan((90-a) * ( 3.1415926 / 180)) * w1
        w=w1
    }
    else if (  a > 90 && a <= ca[1]  ) {
        h=-1 * Math.tan((a-90) * ( 3.1415926 / 180)) * w1
        w=w1
    }
    else if (  a > ca[1] && a <= 180  ) {
        h=h1
        w=-1 * Math.tan((180 - a) * ( 3.1415926 / 180)) * h1
    }
    else if (  a > -180 && a <= (-1 * ca[1])  ) {
        h=h1
        w= Math.tan((a - 180) * ( 3.1415926 / 180)) * h1
    }   
    else if (  a > (-1 * ca[1])  && a <=  0 ) {
        h=Math.tan((a-90) * ( 3.1415926 / 180)) * w1
        w= w1
    }   

    // We now have the width and height offsets - compute the hypotenuse.
    var hp=this.hyp(w, h)
    
    return {hp: hp }    
}       

Connector.prototype.hyp = function hyp(X, Y) {
return Math.abs(Math.sqrt( (X * X) + ( Y * Y) ))
}


Connector.prototype.moved=function moved(e, ele) {
    var id=ele.attr('id');
    this.link()
}





var line;
$( document ).ready(function() {
    console.log( "ready!" );

    var c1=new Connector({ele1: 'a', ele2: 'b', lineStyle: '1px solid red' })
    Setup(c1, 'a');
    Setup(c1, 'b');
    
    var c2=new Connector({ele1: 'a', ele2: 'c', lineStyle: '1px solid red' })
    Setup(c2, 'a');
    Setup(c2, 'c');

    var c3=new Connector({ele1: 'a', ele2: 'd', lineStyle: '1px solid red' })
    Setup(c3, 'a');
    Setup(c3, 'd');
    
    var c4=new Connector({ele1: 'b', ele2: 'c'})
    Setup(c4, 'b');
    Setup(c4, 'c'); 

    var c5=new Connector({ele1: 'b', ele2: 'd'})
    Setup(c5, 'b');
    Setup(c5, 'd'); 
    
    var c6=new Connector({ele1: 'c', ele2: 'd'})
    Setup(c6, 'c');
    Setup(c6, 'd');


    function Setup(connector, id) {
        var ele=$('#'+id);
        ele.on('mousedown.muConnector', function(e){
            
            //#critical: tell the connector about the starting position when the mouse goes down.
            connector.offsets[id].left=e.pageX - ele.offset().left;
            connector.offsets[id].top=e.pageY - ele.offset().top;
        
            e.preventDefault();
            
            //hook the mouse move           
            ele.on('mousemove.muConnector', function(e){
               ele.css({left: e.pageX - connector.offsets[id].left, top: e.pageY - connector.offsets[id].top}); //element position = mouse - offset
              connector.moved(e, ele); // #critical: call the moved() function to update the connector position.
            });
            
            //define mouse up to cancel moving and mouse up, they are recreated each mousedown
            $(document).on('mouseup', function(e){
              ele.off('mousemove.muConnector');
              //$(document).off('.muConnector');
            });
            
        });
    }       

});
.thing {
  width: 200px;
  height: 100px;
  background: transparent;
  position: absolute;
  border: 1px solid #666666;
}

.thing span {
  display: block;
  margin-left: 95px;
  margin-top: 40px;
}

.muConnector {
  position: absolute;
  border-left: 1px dashed red;
  z-index: 100;
  -webkit-transform-origin: top left;
  -moz-transform-origin: top left;
  -o-transform-origin: top left;
  -ms-transform-origin: top left;
  transform-origin: top left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span>Drag any box...</span>

  <div id="a" class='thing' style='left:400px; top: 100px;'>
    <span>o</span>
  </div>
  
  
  <div id="b" class='thing' style='left:600px; top: 300px;'>
    <span>o</span>
  </div>

  <div id="c" class='thing' style='left:400px; top: 500px;'>
    <span>o</span>
  </div>
  
  
  <div id="d" class='thing' style='left:200px; top: 300px;'>
    <span>o</span>
  </div>

3
  • Vue и jQuery это разные вещи. Вопрос задан о реализации с библиотекой Vue - и если предлагается использовать еще и jQuery (что в целом неок идея, т.к. Vue работает с Shadow DOM), то надо хотя бы на словах объяснить такую интеграцию.
    – yar85
    11 окт 2021 в 14:17
  • 1
    Согласен, что в тупую скопировать и вставить в проект на Vue - плохая идея. Прикрепил данный пример с целью показать способ реализации, так как был вопрос как соединить линией два drag and drop блока.
    – Alexandr
    11 окт 2021 в 14:57
  • да все верно нужна реализация именно на VUE , но спасибо за помощь в любом случае!
    – Roman Ag
    12 окт 2021 в 7:39
0

либо как вариант на Canvas, либо может наоборот проще возможность реализовать это, так как по факту на странице будет кнопка + при нажатии на которую будет вылетать список иконок и при добавлении на страницу более 2 иконок они должны двигаться независимо друг от друга и соединяться пунктиром

1
  • В текущем виде ваш ответ непонятен. Пожалуйста, нажмите править под сообщением, чтобы добавить больше подробностей, которые помогут другим понять, как он отвечает на заданный вопрос. Вы можете найти больше информации о том, как писать хорошие ответы в Справке. 14 окт 2021 в 11:28

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.