Script for converting SVG to JSON

Transform a SVG image in JavaScript object to display and animate in Canvas.

In a previous article, we saw how to convert a SVG image to a JavaScript file to be included directly in a Web page, and how to display - much faster - the image in Canvas.

This new script converts the SVG file in a JSON file that can be loaded with Ajax, WebSockets, etc ... The Scriptol runtime (scriptol.org) must be installed.

node svgtojson.js image.svg 

This command convert the SVG file to a JavaScript object and creates the file image.json.

Here's the code to load the file into 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 a single instruction with the minimalist Anaa Ajax framework (on this site).

Content is assigned to the responseText attribute of Ajax and passed as argument to the function setJSON,
The JSON.parse function converts the text in a JavaScript object. A small animation is then performed which uses SVGtoCanvas to display the object in Canvas.

Demonstration

SVG
CANVAS

Download the script and the demo

The archive contains: