Jung
Jung

Reputation: 207

multiple JSON object canvas create multiple Image

var canvas = window._canvas = new fabric.Canvas('ImgCanvas');

function makeallImage(){
    for (var v = 0; v < json.length; v++){
        convertImgToBase64(v, "png");
        console.log(v);
    }
}

function convertImgToBase64(number, outputFormat){
    canvas.loadFromJSON(json[number], canvas.renderAll.bind(canvas), function(){
    interval = setInterval(function() {
    toImg(outputFormat);
    canvas.clear();
    clearInterval(interval);
    }, 1000);
    });
}

function toImg(outputFormat){
    var s = document.getElementById("last_Image");
    var url = canvas.toDataURL();
    var newImg = document.createElement("img"); // create img tag
    newImg.src = url;
    newImg.width = 380;
    newImg.height = 400;
    s.appendChild(newImg);
}

i had multiple json object which i wanted to turn them all to Image and i only wanted to use 1 canvas to create those image. it had to use loadFromJSON.

but my code only create the last object and also keep looping endlessly , which i dont know why. can anyone help me on this? and isit possible ? or good way to create multiple image from canvas ?

any advice or help , i will be appreciate.

check my demo please. after pressing the button scroll down to see the image and endless loop. thank. Demo

Upvotes: 1

Views: 543

Answers (2)

Theo Itzaris
Theo Itzaris

Reputation: 4671

i made some fixes on your code and as you can see ,(screenshot,jsfiddle)the three images are shown on the DOM.

i mainly altered your convertImgToBase64 function. snippet code :

function convertImgToBase64(number, outputFormat){  
    var tmpData = canvas.loadFromJSON(json[number]);
    toImg(tmpData);
}

function toImg(outputFormat){
    var s = document.getElementById("last_Image");
    var url = canvas.toDataURL();
    var newImg = document.createElement("img"); // create img tag
    console.log(newImg);
    newImg.src = url;
    newImg.width = 150;
    newImg.height = 150;
    s.appendChild(newImg);
    console.log('mpike sto dom');
}

live example: http://jsfiddle.net/tornado1979/zzqhhbcq/9/

screenshot: enter image description here

hope helps ,good luck.

Upvotes: 0

1cgonza
1cgonza

Reputation: 1588

The callback on loadFromJSON is actually the second parameter and not the third. Plus there is no need for the setInterval. Try the following:

function convertImgToBase64(number, outputFormat) {
    canvas.loadFromJSON(json[number], function() {
        canvas.renderAll(canvas);
        toImg(outputFormat);
        canvas.clear();
    });
}

The rest of the code is fine.

Upvotes: 1

Related Questions