How Do You Render a Portion of an SVG in Canvas?

Go To


Core Problem:

The goal is to render a portion of an SVG to a fixed size Canvas element on a web page.

My Attempted Solution:

Seeing as CanVG seems to be the most straight-forward way to render an SVG image in Canvas I figured I could leverage the viewBox attribute to crop the image prior to CanVG's rendering. I've been having trouble on this point.

The Question:

Provided an SVG image, how can one render a portion of that image to a Canvas element?

2012-04-04 19:54
by akdom
Is it unacceptable to render the entire SVG to one canvas and then just drawImage a portion of that canvas to another - Phrogz 2012-04-04 21:29
That is not unacceptable in this case, but can one do that with a hidden image as well? Then it wouldn't matter visibly - akdom 2012-04-05 02:40
Using the viewBox sounds like a really good way to go, however. Perhaps it's not properly supported by CanVG, or perhaps you're just doing something wrong. Do you have an example showing what you tried with this and how it failed - Phrogz 2012-04-05 02:48


  1. Create an offscreen canvas and render to it using CanVG:

    var full = document.createElement('canvas');
    full.width=800; full.height=600;
    canvg(full, '<svg>…</svg>');
  2. Copy a portion of this canvas-as-image to a region on another canvas using drawImage (see link for parameter details):

    var ctx = myVisibleCanvas.getContext('2d');

Edit: However, the above is not necessary if you have access to the SVG source (either directly in JS or via an XMLHTTP request) and can modify the viewBox attribute before rendering. See this demo which shows an SVG file rendered directly to one canvas, and then changes the viewBox attribute and renders the clipped region to another canvas.

2012-04-05 02:45
by Phrogz


Which exactly is the problem you get? The context.drawImage function has a nice cropping feature built in. Instead of the standard 3 parameters (image object, x position, y position) you just pass to it 9 parameters and it will crop the image. These are the parameters:

original image x crop position,
original image y crop position,
original image crop width,
original image crop height,
canvas image x crop position,
canvas image y crop position,
canvas image crop width,
canvas image crop height

I have no idea if this works with CanVG but, as long as you can pass an image object to the function drawImage(), you will be able to crop it as mentioned in the code.

2012-04-05 02:07
by Saturnix