Timo
Timo

Reputation: 261

Embedding JPEG in SVG using JavaScript

I am wondering how to include jpg-images in SVG!

var ns = 'http://www.w3.org/2000/svg';
var svg = document.createElementNS(ns, 'svg');
svg.setAttribute('width', 800);
svg.setAttribute('height', 450);

var image = document.createElementNS(ns, 'image');
image.setAttribute('href', 'http://placehold.it/300x300');
image.setAttribute('x', 0);
image.setAttribute('y', 0);
image.setAttribute('width', 800);
image.setAttribute('height', 450);

svg.appendChild(image);
document.body.appendChild(svg);

Where is my mistake?

Upvotes: 0

Views: 66

Answers (1)

Robert Longson
Robert Longson

Reputation: 123985

For Safari you'd need to change

image.setAttribute('href', 'http://placehold.it/300x300');

to

image.setAttributeNS('http://www.w3.org/1999/xlink', 'href', 'http://placehold.it/300x300');

This second way of doing things is Chrome/Firefox compatible too.

Safari may support your way in the future as it's part of the upcoming SVG 2 specification, the second way is the SVG 1.1 way to do things.

Upvotes: 2

Related Questions