2

Quero elaborar um gráfico em que posso mover os pontos (circle) de uma linha em JavaScript. Ao mover o objeto circle, a linha fica sempre colada ao circulo.

Quero fazer do gênero disso:

inserir a descrição da imagem aqui

Ou seja, é uma linha para cada circulo, sendo possível movê-los e obter as suas posições.

O gráfico base é o SVG a seguir, que é uma espécie de plano cartesiano:

<svg id="svg" width=100% height=500px >

    //vertical
    <line title="Vertical" x1=60 y1=60 x2=60 y2=450 stroke-width=2 stroke=black /> 

    //text vertical
    <text x=60 y=60 text-anchor=end fill=black ><?php echo $txtmaxresistance." Ohm";?></text>
    <text x=55 y=450 text-anchor=end fill=black ><?php echo $txtminresistance;?></text>

    //horizontal
    <line title="Horizontal" x1=60 y1=450 x2=450 y2=450 stroke-width=2 stroke=black /> 

    //text horizontal
    <text x=470 y=465 text-anchor=end fill=black ><?php echo $txtmaxtemp." Temp";?></text>
    <text x=80 y=465 text-anchor=end fill=black ><?php echo $txtmintemp;?></text>

    <line title=<?php echo $txtnome;?> x1=400 y1=90 x2=60 y2=450  stroke-width=2 stroke=black />    


</svg>

O código a seguir cria os vários círculos (pontos) em cima de uma reta:

var svg = document.querySelector('svg');

        for (var i = 0; i < step; i++) {
            var x = 30*i;
            var y = 30*i;
            var shape = document.createElementNS("http://www.w3.org/2000/svg", "circle");
            shape.setAttributeNS(null, "cx", 100+x);
            shape.setAttributeNS(null, "cy", 400-y);
            shape.setAttributeNS(null, "r", 5);
            shape.setAttributeNS(null, "fill", "green");
            svg.appendChild(shape);
        }

1 Resposta 1

4

Com alguns ajustes de posicionamento no gráfico, fiz uma implementação simples usando JavaScript puro, permitindo arrastar e soltar os vértices e fazendo a linha acompanhar esse movimento.

Veja a implementação a seguir:

var svg = document.querySelector('svg');

//data to control drag'n drop 
var ddData = {
    element: null,
    initialX: 0,
    initialY: 0, 
    originalX: 0,
    originalY: 0,
    lineEnd: null,
    lineStart: null
};

//number of dots on the line
var steps = 10, originX = 60, originY = 450;

//distance between circles
var stepX = (450 - 60) / (steps + 1);
var stepY = stepX;

//create lines
var lines = [];
for (var i = 0; i <= steps; i++) {
    var x1 = stepX * i, x2 = stepX * (i + 1);
    var y1 = stepY * i, y2 = stepY * (i + 1);
    
    var line = document.createElementNS( 
        "http://www.w3.org/2000/svg", "line");
    line.setAttributeNS(null, "x1", originX + x1);
    line.setAttributeNS(null, "y1", originY - y1);
    line.setAttributeNS(null, "x2", originX + x2);
    line.setAttributeNS(null, "y2", originY - y2);
    line.setAttributeNS(null, "stroke", "red");
    line.setAttributeNS(null, "stroke-width", "2");
    svg.appendChild(line);
    
    lines[i] = line;
}

//create dots
for (var i = 0; i < steps; i++) {
    var x = stepX * (i + 1);
    var y = stepY * (i + 1);
    
    //create circle
    var shape = document.createElementNS(
        "http://www.w3.org/2000/svg", "circle");
    shape.setAttributeNS(null, "cx", originX + x);
    shape.setAttributeNS(null, "cy", originY - y);
    shape.setAttributeNS(null, "r", 5);
    shape.setAttributeNS(null, "fill", "green");
    shape.setAttributeNS(null, "class", "draggable");
    shape.setAttributeNS(null, "order", i);
    svg.appendChild(shape);
    
    //start moving circle
    shape.onmousedown = function(evt) {
        var evt = evt || window.event;
        ddData.element = evt.target || evt.srcElement;
        ddData.initialX = evt.clientX;
        ddData.initialY = evt.clientY;
        ddData.originalX = parseFloat(
            ddData.element.getAttributeNS(null, "cx"));
        ddData.originalY = parseFloat(
            ddData.element.getAttributeNS(null, "cy"));
        var order = parseInt(
            ddData.element.getAttributeNS(null, "order"));
        ddData.lineEnd = lines[order];
        ddData.lineStart = lines[order+1];
    };
}

//handle mouse movement to drag circles
svg.onmousemove = function(evt) {
    var evt = evt || window.event;
    if (ddData.element) {
        var posX = ddData.originalX + evt.clientX - ddData.initialX;
        var posY = ddData.originalY + evt.clientY - ddData.initialY;
        //move object
        ddData.element.setAttributeNS(null, "cx", posX);
        ddData.element.setAttributeNS(null, "cy", posY);
        //move line before
        ddData.lineEnd.setAttributeNS(null, "x2", posX);
        ddData.lineEnd.setAttributeNS(null, "y2", posY);
        //move line after
        ddData.lineStart.setAttributeNS(null, "x1", posX);
        ddData.lineStart.setAttributeNS(null, "y1", posY);
    }
};

//stops drag movement
svg.onmouseup = function(evt) {
    var evt = evt || window.event;
    ddData.element = null;
}
.draggable {
    cursor: move;
}
<svg id="svg" width=100% height=500px >
    <line title="Vertical" x1=60 y1=60 x2=60 y2=450 stroke-width=2 stroke=black /> 
    <text x=60 y=60 text-anchor=end fill=black >10 Ohm</text>
    <text x=55 y=450 text-anchor=end fill=black >12</text>

    <line title="Horizontal" x1=60 y1=450 x2=450 y2=450 stroke-width=2 stroke=black /> 
    <text x=470 y=465 text-anchor=end fill=black >100 Temp</text>
    <text x=80 y=465 text-anchor=end fill=black >1</text>

    <line title="Teste" x1=450 y1=60 x2=60 y2=450  stroke-width=2 stroke=black />    
</svg>

O código é meio grande para explicar em detalhes, mas deixei alguns comentários no meio dele e espero que esteja fácil de ler.

Tirei uma ou duas ideias deste link. Veja também um exemplo mais avançado com linhas curvas usando a biblioteca d3.

7
  • Obrigado, bom codigo. Como posso obter agora a posiçao de cada um dos pontos?
    – akm
    2/12/2014 às 16:17
  • @akm Basta recuperar uma referência ao objeto criado de alguma forma e usar o trecho parseFloat(ponto.getAttributeNS(null, "cx")). Faça o mesmo para a posição cy.
    – utluiz
    2/12/2014 às 16:20
  • estou a utilizar var x=parseFloat(ddData.element.getAttributeNS(null, "cx")); dentro da função do onmousemove.
    – akm
    2/12/2014 às 16:33
  • @akm Dentro da função funciona porque o ddData.element tem referência para o círculo clicado. Se quiser recuperar a posição de outros círculos ou de todos eles, terá que recuperar essas referências de outro lugar. Não sei para que você quer isso exatamente, mas uma ideia simples é armazenar todos os círculos num vetor, aí você pode fazer um loop e recuperar a posição de cada um.
    – utluiz
    2/12/2014 às 16:35
  • Sim quero recuperar a posição de todos os circulos, para depois guardar a sua posição x e y depois de movidos num ficheiro.
    – akm
    2/12/2014 às 16:40

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .