1

With RaphaelJS, this command inserts an image:-

var myImg = paper.image('image.svg', 100, 100, 150,150);

and the SVG output is:-

<image x="100" y="100" width="150" height="150" preserveAspectRatio="none" href="image.svg"/>

Question: How do I directly access preserveAspectRatio attribute and change it to xMidYMid meet - if you examine myImg.attr(), it doesnt show this attribute.

The roundabout way is navigate the SVG DOM tree, and execute svgImg.setAttributeNS(null,"preserveAspectRatio" , "xMidYMid meet" );

Note: Only some images require none while the rest needs the xMidYMid meet tag. Hence I can't set this attribute on parent <svg>

Note2: Chrome doesn't support preserveAspectRatio with SVG images. Use FF or IE to test.

Community
  • 1
  • 1
Alvin K.
  • 4,329
  • 20
  • 25

2 Answers2

1

At the source code level, preserveAspectRatio is hardcoded to none

Answer The quickest way to change this:-;

myImg[0].preserveAspectRatio.baseVal.align = 6     (1 = off, 6 = xMidYMid) myImg[0].preserveAspectRatio.baseVal.meetOrSlice = 1     (1 = meet, 2 = slice)

Update:- jQuery style:-

jQuery(myImg.node).prop('preserveAspectRatio').baseVal.align = 6 ; jQuery(myImg.node).prop('preserveAspectRatio').baseVal.meetOrSlice = 1 ;

Raphael's docs for Element.node "Gives you a reference to the DOM object, so you can assign event handlers or just mess around. Note: Don’t mess with it."

Alvin K.
  • 4,329
  • 20
  • 25
  • I'm pretty sure jQuery wont work in setting `preserveAspectRatio` because jQuery decapitalizes attribute names before inserting them into the DOM, and SVG, being strict XML, is case sensitive. he will need to use the native DOM methods directly – Owen Masback May 02 '13 at 02:29
  • You're correct, updating the jQuery answer. The other alternative is to edit (in 4 places) raphael.js to accept preserveAspectRatio. – Alvin K. May 02 '13 at 03:31
0

You can call these parameters on the Raphael canvas as a whole.

First create SVG: var paper = Raphael('content',xSize,ySize);

Place image in it: paper.image('image.svg', 100, 100, 150,150);

Then change attributes of svg: paper.canvas.setAttribute('preserveAspectRatio', 'xMidYMid meet');

Fra
  • 393
  • 7
  • 19