1

I am trying to render a svg image with knockout, but it is not showing image after I successfully bound the viewmodel.

Here is the SVG

<svg width="500" height="500" style="border: solid 1px black">

<image id="img1" width="500" height="500"
        data-bind="attr:{'xlink:href': image}"></image>
</svg>

Here is the knockout bindings,

<script>
    var viewModel = function(data){
        var self = this;
        self.image = ko.observable(data.image)
    };

    var data = {image: "http://2.bp.blogspot.com/-cGeVTe2XeWU/VUEiQidIJKI/AAAAAAAACwU/UYzCrcNMMAk/s1600/comic.png"};

    var vm = new viewModel(data);
    ko.applyBindings(vm);
</script>

Anyway I checked the page source after executing this code. So the SVG image element in page source is

<image id="img1" width="500" height="500" data-bind="attr:{'xlink:href': image}" xlink:href="http://2.bp.blogspot.com/-cGeVTe2XeWU/VUEiQidIJKI/AAAAAAAACwU/UYzCrcNMMAk/s1600/comic.png"></image>

As you can see here, it is setting xlink:href correctly, but it is not showing on svg.

Do I need to refresh DOM somehow? Simply how can I render SVG image using knockout?

Any help will be appreciated

mili
  • 3,502
  • 1
  • 29
  • 29

2 Answers2

2

xlink:href attribute needs to be there even with empty value to initialize the HTML svg image.

so image tag should be like Here is a demo and more info

  <image id="img1" width="500" height="500" xlink:href=""
        data-bind="attr:{'xlink:href': image}"></image>
mili
  • 3,502
  • 1
  • 29
  • 29
1

SVG elements are not added to the DOM when you use an img element to display the image, therefore knockout.js is unable to bind to those elements. The answers to this question contain some solutions that might help you: How do you access the contents of an SVG file in an <img> element?

Note: I get this solution from Stackoverflow.

Community
  • 1
  • 1