I can move an SVG object with the mouse in JavaScript, I would now like to move an image of type png or svg.
<svg>
<image xlink:href=image.png x=0 y=0 height=20 width=20 />
</svg>
Functional code when moving objects svg: link
I can move an SVG object with the mouse in JavaScript, I would now like to move an image of type png or svg.
<svg>
<image xlink:href=image.png x=0 y=0 height=20 width=20 />
</svg>
Functional code when moving objects svg: link
Done, watch comments.
var svg = document.querySelector('svg');
//create rect
var shape = document.createElementNS(
"http://www.w3.org/2000/svg", "image");
svg.appendChild(shape);
svg.addEventListener('mousedown', mousedown);
var ddData = {
element: null,
initialX: 0,
initialY: 0,
originalX: 0,
originalY: 0
};
//start move
function mousedown(evt) {
var evt = evt || window.event;
ddData.element = evt.target || evt.srcElement;
if (!ddData.element.id) return ddData.element = null;
ddData.initialX = evt.clientX;
ddData.initialY = evt.clientY;
// adicionei verificação de tag image, com o mesmo tratamento do retangulo.
ddData.originalX = parseFloat(ddData.element.getAttributeNS(null, ddData.element.tagName == 'rect' || ddData.element.tagName == 'image' ? 'x' : 'cx'));
ddData.originalY = parseFloat(ddData.element.getAttributeNS(null, ddData.element.tagName == 'rect' || ddData.element.tagName == 'image' ? 'y' : "cy"));
};
svg.onmousemove = function(evt) {
var evt = evt || window.event;
var el = ddData.element;
if (el) {
var posX = ddData.originalX + evt.clientX - ddData.initialX;
var posY = ddData.originalY + evt.clientY - ddData.initialY;
// adicionei verificação de tag image, com o mesmo tratamento do retangulo.
if (el.tagName == 'rect' || el.tagName == 'image') {
//move object
el.setAttributeNS(null, "x", posX);
el.setAttributeNS(null, "y", posY);
} else {
el.setAttributeNS(null, "cx", posX);
el.setAttributeNS(null, "cy", posY);
}
}
}
//stops drag movement
svg.onmouseup = function(evt) {
var evt = evt || window.event;
ddData.element = null;
}
<svg width="90%" height=500px>
<rect id=1 ry=0 rx=0 x=50 y=50 width=20px height=20px fill=red />
<!-- adicionei um id -->
<image id=2 xlink:href='http://i.stack.imgur.com/ZM8xJ.png' x=0 y=0 height=20 width=20 />
<svg>
This question is similar to other questions you have already asked. You changed small details that should be part of the original question.
The problem with this code is that you are using image
and no longer circle
as you had before. Just as both rect
and image
use coordinates x|y
the ddData.element.tagName == 'rect' ? 'x' : 'cx')
check is no longer correct. You should change to ddData.element.tagName != 'circle'
.
In the other question you also had IDs on the elements you wanted to move, hence you had the line of code if (!ddData.element.id) return ddData.element = null;
that now no longer makes sense.
Correcting these lines results in: link