svg PShape wrong position

edited October 2013 in Questions about Code

I'm using PShape to draw an .svg image, but when I try to put it in the corner it ends up around the middle of the page.

I've tried to make sure there's no white space around the image by editing it in Illustrator, and opening it in Internet Explorer as a test it is shown in the top left corner.

Does anyone know why? Does processing read some information that Explorer doesn't, or is there something wrong with the code? Here it is:

PShape svg;

 void setup() {
    size(800, 480);
    svg = loadShape("cliff1_j.svg");
 }

 void draw() {

 background(0);
 shape(svg, 0, 0);
}

Answers

  • Try experimenting with shapeMode().

    Also would be great if you can post your svg so that it is possible to test it.

  • edited October 2013

    Thanks for the answer!

    I already played around with shapeMode() (although I forgot to say so in the OP). How do you share files on this board? Here's a download link to the file:

    https://dl.dropboxusercontent.com/u/23686355/cliff1_j.svg

  • PShape svg;
    
    void setup() {
      size(800, 480);
      svg = loadShape("H:/Temp/cliff2_j.svg");
    }
    
    void draw() {
    
      background(0);
      translate(-257.04, -112.808); // Values taken from the viewBox attribute of the SVG file
      shape(svg, 0, 0);
    }
    

    The SVG has a viewBox attribute, set to the dimensions of the image (so, no scaling), but translating it to compensate the coordinates of the path points.

    By translating by the values seen in this attribute, we can draw the image at 0, 0.

    Perhaps Processing should take in account this attribute, like Firefox or Inkscape do.

  • Answer ✓

    Automation of the above:

    PShape svg;
    
    String path = "H:/Temp/cliff2_j.svg";
    float[] viewBox;
    
    void setup() 
    {
      size(800, 480);
      viewBox = getViewBox(path);
      svg = loadShape(path);
    }
    
    void draw() 
    {
      background(0);
      translate(-viewBox[0], -viewBox[1]);
      shape(svg, 0, 0);
    }
    
    float[] getViewBox(String path)
    {
      float[] viewBox = { 0, 0, 0, 0 };
    
      XML xml = loadXML(path);
      String viewBoxStr = xml.getString("viewBox");
      println(viewBoxStr);
      if (viewBoxStr != null) 
      {
        viewBox = float(split(viewBoxStr, ' '));
      }
      return viewBox;
    }
    
  • That is actually a very useful piece of information, @PhiLho. I was wondering how to deal with that.

  • That's great, thank you so much! This board keeps impressing me

  • Just registered specifically to say a huge thank you for asking the question @jorgen and your detailed answer @PhiLho, just saved me from a massive headache with the exact same problem.

Sign In or Register to comment.