SVG Conversion Script - JSON

Converts an SVG image to a JavaScript object for display or animation in Canvas.

In the previous article, we saw how to convert an SVG image to a JavaScript file for inclusion in a web page to show - much faster - the image in Canvas.

This new script converts the SVG file into a JSON file that can be downloaded using Ajax, WebSocket, etc. An execution script must be installed.

node svgtojson.js image.svg 

This command converts SVG to JavaScript and creates the image.json file.

Here is the code to upload the file to the page and display it in Canvas...

SVG display:

<object id="carsvg" width="400" height="100" data="car-json.svg"></object>

Display in Canvas with animation:

<canvas id="jsoncar" width="500" height="100"></canvas>
var car;
var x = 50;
var drawInter;

function redraw(ctx) {
  ctx.clearRect(0, 0, 500, 100);
  SVGtoCanvas(car, ctx, x++, 20);
  if(x > 300) clearInterval(drawInter);
}

function setJSON(content) {
  car = JSON.parse(content)
	
  var ctx = canvasInit("jsoncar")
  SVGtoCanvas(car, ctx, 50, 20);
	
  drawInter = setInterval(function() { redraw(ctx) }, 10);
}

AARead("car.json", setJSON, null);

The JSON file is loaded in one instruction with the minimalistic Ajax Anaa framework (on this site ).

The content is assigned to the responseText Ajax attribute and passed as an argument to the setJSON function.
The JSON.parse function converts this text content into a JavaScript object. A small animation is then created that uses SVGtoCanvas to display the object in Canvas.

Display

SVG
CANVAS

Download script and demo

The archive contains: