Clone of an image

Asked

Viewed 64 times

2

I have the code that moves SVG images with the mouse. When I move the image, as soon as it is released, I want your clone to appear, in the position that the first one started and that it is also possible to move it. I have an example here, with the clone code that doesn’t work for me:

var newimage = document.getElementById('img').cloneNode(true);

Example: http://jsfiddle.net/kpvgkrey/3/

2 answers

2

You almost got it right, you just got it wrong when you gave the appendchild, you’re trying to append the body, when you should append the svg root, try the following:

HTML:

<svg width="90%" height=500px id="svgRoot">
    <image xlink:href=/favicon.png id="img" x=0 y=0 height=20 width=20 />
<svg>

Javascript:

function clone() {
    var root = document.getElementById('svgRoot');
    var newimage = document.getElementById('img').cloneNode(true);

    newimage.setAttribute("x", ddData.initialX);
    newimage.setAttribute("y", ddData.initialY);
    newimage.style.position = 'absolute';
    newimage.id = 'novoSVG';

    root.appendChild(newimage);
}

@Edit: Functional Jsfiddle: https://jsfiddle.net/ee2ss3x4/1/

  • If you put an example of your code to work, it becomes easier to check if it solves the problem and so receive the deserved reputation ;)

  • Okay, I added it to Edit :)

2


You can clone directly when you "grab" an element, in the mousedown.

Then all you need is a new line:

ddData.element.parentNode.appendChild(ddData.element.cloneNode(true));

Example: http://jsfiddle.net/ra4ega92/

Ps: I added one more check here because of errors I was giving when the click was not on an image:

if (!ddData.element || ddData.element.tagName == 'svg') return ddData.element = null;
  • That’s right, but I need a different id on each element to hold its position. And creates a clone for all of them, even those who were moved.

  • @akm and what ID do you want to give? what is the standard you want to follow?

  • I need to store the x and y position of each moved object in an array, less than the one in the position (0,0). Of the already created objects, no more can be created. Only if you move the object from the top again.

  • @akm take a look here: http://jsfiddle.net/twsthyds/ is what you want?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.