holyredbeard
holyredbeard

Reputation: 21198

Change image (svg) on click

I'm trying out Raphael + vectron, and i'm trying to change a svg image with a button click.

This is (of course) not possible due to that when the svg is rendered it's rendered as path:

<path cx="100" d="M35.269,257.154C34.393,245.68099999999998,45.438,234.091,48.492,223.00799999999998C53.634,204.34099999999998,54.985,185.004,60.041 and so on...... " stroke="none" fill="#9d49ce" style=""></path>

Below is the code, which would work if I was working with a normal image (like .png), but the question is how can I change the svg image with Raphael (and vectron).

html:

<div id="container">
 <div id="avatarBox" class="bgBox_blue">
  <div id="charBody" class="svg-file" data-svg="img/body1.svg"></div>
 </div>
 <div id="toolBox">
  <div class="toolboxArea">
    Byt kropp<br/>
    <button id="moveLeftBtn"><</button>
    <button id="moveRightBtn">></button>
    <div class="clear"></div>
  </div>

js:

$('.svg-file').vectron({
    scale: 1
  }).ajaxSuccess(function(){
    $('svg').attr({
      'height': ($('svg').attr('height')*120)/100,
      'width': ($('svg').attr('width')*110)/100,
    });

    var paper = $('.svg-file').data('vectron').paper;
    var unicorn = paper.top;

    $('.bodyBg').live('click', function(){
      unicorn.attr({
        fill: $(this).val(),
        cx: 100
      });
    });
  });


var moveRightBtn = $('#moveRightBtn');
    moveRightBtn.on('click', function(){
        var newImage = 'body' + (AvatarGenerator.eyes + 1) + '.svg';
        $('#charBody').attr('data-svg','img/' + newImage);
    });
});

Upvotes: 4

Views: 2408

Answers (1)

user568109
user568109

Reputation: 47993

You can wrap the path inside svg tag.

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<path cx="100" d="M35.269,257.154C34.393,245.68099999999998,45.438,234.091,48.492,223.00799999999998C53.634,204.34099999999998,54.985,185.004,60.041 and so on...... " stroke="none" fill="#9d49ce" style=""></path>
</svg>

It will behave as an svg element. I tested it on Chrome and IE.

So in your case, given an HTML file with this line :

<div id="charBody" class="svg-file" data-svg="img/body1.svg"></div>

Calling $('.svg-file').vectron(); creates a child svg element for charBody with content loaded from the file, which is displayed in the page.

I would say instead of calling vectron you can directly add the content from the svg element string to that div's innerHTML where you wish to add SVG.

vectron was last updated a year ago, so I don't have high hopes from it. Besides you only need to change an svg on buttonclick which can be done without vectron easily.

Upvotes: 2

Related Questions