Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 986
akdom Avatar asked Apr 04 '12 19:04

akdom


2 Answers

  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');
    ctx.drawImage(full,10,20,80,60,92,16,80,60);
    

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.

like image 181
Phrogz Avatar answered Oct 18 '22 09:10

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:

context.drawImage(
imageObject,
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.

like image 39
Saturnix Avatar answered Oct 18 '22 11:10

Saturnix