pavan
pavan

Reputation: 1065

How to dynamically create svg element and animate a image

I have a requirement on page load I need to create an 'Image' attribute and append it to the svg element to start animation. However, I tried to create Image and associated animate element and attach it to the svg element.The image is getting displayed on the page however it is not getting animated.

Can any one pls help in this.

code added at http://jsbin.com/dofun/1/edit?html,js,output

Thanks Pavan Kumar

Upvotes: 0

Views: 2410

Answers (1)

Robert Longson
Robert Longson

Reputation: 124289

Setting a duration for an animation is mandatory. If you add

animate.setAttribute('dur', '3s');

it animates correctly for me provided I add an svg element with an appropriate id.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <svg width="100%" height="100%" id="svg_image"/>
</body>
</html>

body, html {
  width : 100%;
  height: 100%;
}

var img = document.createElementNS('http://www.w3.org/2000/svg','image');
    img.setAttributeNS(null,'height','536');
img.setAttributeNS(null,'width','536');
img.setAttributeNS('http://www.w3.org/1999/xlink','href','https://upload.wikimedia.org/wikipedia/commons/2/22/SVG_Simple_Logo.svg');
img.setAttributeNS(null,'x','10');
img.setAttributeNS(null,'y','10');
img.setAttributeNS(null, 'visibility', 'visible');
img.setAttributeNS(null,'id','image_test');


// animate object

var animate = document.createElementNS('http://www.w3.org/2000/svg','animate');
animate.setAttributeNS(null,'attributeName','x');
animate.setAttributeNS(null,'from',500);
animate.setAttributeNS(null,'to',0);
animate.setAttribute('dur', '3s');
//append animate with image
img.appendChild(animate);

document.getElementById("svg_image").appendChild(img);

Upvotes: 1

Related Questions