cooldude
cooldude

Reputation: 985

Converting HTML TAG Object to JSON Object

I want to convert the html tag objects to json object in the javascript in order to send them to the server from the javascript. As i have to save these objects at the Ruby on Rails server. These HTML objects is the canvas tag object and the graphics objects created using CAKE API. I have used the stringify function but it is not working. Here is my code:

window.onload=function()
{
    var CAKECanvas = new Canvas(document.body, 1000,1000);
    var canvas=CAKECanvas.canvas;
    var text=document.createElement('textarea');
    text.id="text";
    text.rows="100";
    text.cols="200";
    document.body.appendChild(text);
    canvas.style.borderStyle="solid";
    canvas.style.borderColor="black";
var rect= new Circle();
    rect.radius=100;
    rect.centered=true;
    rect.cx=Math.random() * 500;
    rect.cy= Math.random() * 300;
    rect.stroke= false;
    rect.fill= "red";
    rect.xDir = Math.random() > 0.5?1:-1;
rect.yDir = Math.random() > 0.5?1:-1;
    var obj=new Object;
    var count = 0,k;
    for (k in rect)
        {
            if (rect.hasOwnProperty(k))
                {
                    count++;
                    obj[k]=rect[k];
                }
        }
    alert(count);
rect.addFrameListener(function(t, dt)
    {
                this.cx += this.xDir * 50 * dt/1000;
        this.cy += this.yDir * 50 * dt/1000;
        if (this.cx > 550)
        {
            this.xDir = -1;
        }
        if (this.cx < 50)
        {
            this.xDir = 1;
        }
        if (this.cy > 350)
        {
            this.yDir = -1;
        }
        if (this.cy < 50)
        {
            this.yDir = 1;
        }
    }
);

CAKECanvas.append(rect);
    var carAsJSON = JSON.stringify(obj); /////////////////NOT CONVERTING THE OBJECT OBJ     INTO JSON OBJECT
}

Upvotes: 1

Views: 3304

Answers (1)

Sean Kinsey
Sean Kinsey

Reputation: 38046

Only primitive values (strings, dates, booleans, numbers) and objects and array structures are possible to serialize into JSON. This mean that other host-objects like RegExp or Canvas cannot be serialized.

In short, JSON is limited to data ('information').

So, you will either have to save the created markup using .innerHTML, or save the data so that it can be recreated.

Upvotes: 1

Related Questions