0

I am using svg.js to draw lines on like a canvas. Is it possible to scale the svg element created by calling SVG() to the size of the parent? As of right now, I am just redrawing all the lines when the element resizes.

<div
  ref={r => this.whiteboard = r}
  id="whiteboard"
  >
</div>
{...}
let { offsetWidth: width, offsetHeight: height } = this.whiteboard;
this.draw = SVG('whiteboard').size(width, height);

I am using React which I know will be hard to mix with svg.js but that is another conversation.

5

1 Answer 1

1

Use SVG.ViewBox

http://svgjs.dev/geometry/#svg-viewbox

For example, something like:

this.draw = SVG('whiteboard').size(width, height).viewbox(0,0,500,300);

The actual values you pass will depend on what you are drawing, and where it is on the canvas. The viewBox() parameters are: minX, minY, width, and height.

3
  • getting "TypeError: this.draw.viewBox is not a function". The method is actually viewbox. Everything is scaling, but they are also moving as the parent resizes. e.g. Initially there's a square in the corner. As the parent gets smaller, the square gets smaller, but it also translates to the right.
    – sdfsdf
    Commented Mar 20, 2018 at 20:32
  • Sorry for the typo. I have fixed my answer. Smaller how? Post an example. That behaviour may be correct, depending on how you are resizing the parent. [Read about how viewBox and preserveAspectRatio works, ](w3.org/TR/SVG/single-page.html#coords-ViewBoxAttribute) Commented Mar 20, 2018 at 21:51
  • This is the correct answer. If you need to scale or translate the visible area of your svg use viewbox. A good article to learn more is justinmccandless.com/post/making-sense-of-svg-viewboxs-madness
    – Fuzzyma
    Commented May 3, 2018 at 8:37

Not the answer you're looking for? Browse other questions tagged or ask your own question.