Search code examples
javascriptsvghtml5-canvaskineticjs

svg images don't scale properly on canvas


Question Now I have been able to fix the problem

I am drawing an .svg image on a canvas using kineticjs. For the image does not seem to scale properly. The scale is not the size I am specifying.

var imageObj = new Image();
imageObj.onload = this.checkAllImagesLoaded.bind(this);
imageObj.src = imageSrc;

then in the checkAllImagesLoaded

var KI = new Kinetic.Image({
                                  image: imageObj,
                                  x: 100,
                                  y: 100,
                                  height: 30,
                                  width: 30
                                  });

The image scales fine when I put it in an html image tag.

Question Before I knew the answer

I am adding images to a stage and I set the height and width.

When I add a .png everything sizes correctly. When I use an svg the image appears tiny. it is as if there is a lot of padding around the image. instead of the 30 pixels I am expecting. if I multiply the height and width by 4 they show up about the size I am expecting.

var imageObj = new Image();
imageObj.onload = this.checkAllImagesLoaded.bind(this);
imageObj.src = imageSrc;

then in the checkAllImagesLoaded

var KI = new Kinetic.Image({
                                  image: imageObj,
                                  x: 100,
                                  y: 100,
                                  height: 30,
                                  width: 30
                                  });

the same svg files when used as the src of an img tag show up and size correctly.

This is happening on ios using cordova so it is essentially a webkit browser.

I have been able to find that some svg files work. I tried an experiment where I copied the contents of an svg file that works and replaced the content of one that doesn't work. Even with the new content and it still showed up small. I tried the reverse taking an svg that doesn't work and copying all the content into a file that works. Then everything works fine.


Solution

  • I fixed this problem by having different svg on the canvas and in the img Tag.

    I had an image tag on my html page that loaded the svg. If I then tried to add a new image pointing to the same file to the canvas (with kineticjs) the svg did not scale properly.

    If I had two copies of the same svg file and put one in the img tag and loaded the other one to the canvas everything scales properly.