jonobr1 / two.js

A renderer agnostic two-dimensional drawing api for the web.
https://two.js.org
MIT License
8.29k stars 454 forks source link

How to scale an imported svg to fit within the scene size #590

Closed marcuskielly closed 2 years ago

marcuskielly commented 2 years ago

I'm creating a scene that is constrained to square dimensions. I'm loading svg assets from files into the scene - but once they are loaded, they are rendering far larger than the available area. I've tried setting the fitted option but that doesn't seem to be affecting the size of the svgs once loaded. I am able to play with the scale of the elements, but this value is arbitrary based on the size of the svg itself.

Is there a means to automatically fit the svg to the size of the stage - or should I re-export them with similar dimensions to the target area?

jonobr1 commented 2 years ago

Thanks for your question. Without a tangible example it's hard to know exactly what would be the best way to remedy the situation. But, in general you should be able to do something like this:

var svg = two.load('path/to/image.svg', loaded);

function loaded() {
  var rect = svg.getBoundingClientRect();
  rect.scale = two.width / rect.width; // Should make the SVG the width of the scene.
}
marcuskielly commented 2 years ago

Ah, my bad. The original svgs were all exported from a single file 2048px square. All I had to do was divide the target stage dimensions by the original size, and that gave me the appropriate scale to resize everything at once. I put this in the resize handler and everything is working fine :)

const scaleElements = (two) => {
  const size = getStageSize(); 
  const original = 2048;
  const scale = size / original;
  two.scene.children.forEach((child) => {
    child.center();
    child.translation.set(two.width / 2, two.height / 2); 
    child.scale = scale;
  })
  two.update();
}

Thanks for getting back to me