Skip to content
This repository


Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Convert Raphaël paper objects to JSON and back

branch: master

Merge pull request #18 from zcourts/master

add support for complicated papers that can result in circular references
latest commit 7d50f2a95a
Elbert Alias authored
Octocat-spinner-32 Updated README September 05, 2012
Octocat-spinner-32 raphael.json.js add support for complicated papers that can result in circular refere… September 21, 2013


Convert Raphaël 2.0 elements on a paper to JSON and back.

This plugin can be used to save the state of a paper for later re-use. It was originally forked from Jonathan Spies's raphael.serialize and later rewritten from scratch to work with Raphaël 2.0.

Licensed under the MIT license.


<script type="text/javascript" src="raphael-min.js"></script>
<script type="text/javascript" src="raphael.json.js"></script>

<div id="holder"></div>

<script type="text/javascript">
    var paper = Raphael('holder');

    var rect = paper
        .rect(50, 50, 50, 50)
        .attr('fill', '#f00')

    var json = paper.toJSON();


    paper = Raphael('holder');



A callback function can be used to save and restore custom attributes.

var json = paper.toJSON(function(el, data) { =;

    return data;
paper.fromJSON(json, function(el, data) { =;

    return el;

Preserving sets

var paper = Raphael('holder');

// Create a set
var exampleSet = paper.set();

var rect = paper.rect(50, 50, 50, 50)
    .attr({ fill: 'red' })


// Store a unique identifier in each of the set's elements
for ( i in exampleSet ) {
    exampleSet[i].setName = 'exampleSet';

// Serialize the paper
var json = paper.toJSON(function(el, data) {
    // Save the set identifier along with the other data
    data.setName = el.setName;

    return data;

// Start over

exampleSet = null;

// Restore the paper to the previous state using serialized data
paper.fromJSON(json, function(el, data) {
    // Recreate the set using the identifier
    if ( !window[data.setName] ) window[data.setName] = paper.set();

    // Place each element back into the set

    return el;

// The set is restored

Raphaël.JSON and Raphaël.FreeTransform

Raphaël.JSON can be used together with Raphaël.FreeTransform to save and load drawings.

// Save
var json = paper.toJSON(function(el, data) {
    data.ft = {};

    if ( el.freeTransform != null ) {
        data.ft.attrs = el.freeTransform.attrs;


    return data;

// Start over

// Load
paper.fromJSON(json, function(el, data) {
    if ( data.ft && data.ft.attrs ) {

        el.freeTransform.attrs = data.ft.attrs;


    return el;
Something went wrong with that request. Please try again.