How to save image with canvas in fabric.js

I am creating a T-shirt customization application in which I put the canvas on an image using CSS, but the problem is to save this image as a canvas. toDataURLjust gives away part of the canvas area, but I want the whole image. There are other solutions in Qaru, but they do not solve this problem.

enter image description here

+4
source share
1 answer

enter image description here Hello, you need to create an image object (tshirt) with a text object that contains a message.

  • fabric.Image.fromURL() , , tshirt. .
  • , , loadText .
  • 4 , manupulate ///.
  • + + saveImg(), jsfiddle . , , , - - .

  • :

     var canvas = new fabric.Canvas('c');
     var scaleFactor=0.4
    
     canvas.backgroundColor = 'yellow';
     canvas.renderAll();
     var myImg = 'http://izy.urweb.eu/files/tshirt.jpg';
    
    
    
     fabric.Image.fromURL(myImg, function(myImg) {
    var img1 = myImg.scale(scaleFactor).set({ left: 0, top: 0 });
    
    var text = new fabric.Text('the_text_sample\nand more', {
                fontFamily: 'Arial',
                fontSize:20,
            });
    
    text.set("top",myImg.height*scaleFactor-myImg.height*scaleFactor+150);
    text.set("left",myImg.width*scaleFactor/2-text.width/2);
    
    var group = new fabric.Group([ img1,text ], { left: 10, top: 10 });
    canvas.add(group);    
    });
    
    
    $('#loadText').on('click',loadText);
    $('#saveImg').on('click',saveImg);
    
    function loadText(){
      console.log($('#logo').val());
       canvas._objects[0]._objects[1].text = $('#logo').val();
       canvas.renderAll();
    }
    
    
    function saveImg(){    
    console.log('export image');
     if (!fabric.Canvas.supports('toDataURL')) {
      alert('This browser doesn\'t provide means to serialize canvas to an image');
    }
    else {
      window.open(canvas.toDataURL('png'));
    }
    }
    
    $('#left').on('click',function(){
    canvas._objects[0]._objects[1].set('left',canvas._objects[0]._objects[1].left-1);
    canvas.renderAll();
    })
    
    $('#right').on('click',function(){
    canvas._objects[0]._objects[1].set('left',canvas._objects[0]._objects[1].left+1);
    canvas.renderAll();
    })
    
    
    $('#top').on('click',function(){
    canvas._objects[0]._objects[1].set('top',canvas._objects[0]._objects[1].top-1);
    canvas.renderAll();
    })
    
    $('#bottom').on('click',function(){
    canvas._objects[0]._objects[1].set('top',canvas._objects[0]._objects[1].top+1);
    canvas.renderAll();
    })
    
  • jsfiddle: http://jsfiddle.net/tornado1979/zrazuhcq/1/

, .

+6

Source: https://habr.com/ru/post/1599872/


All Articles