d0utone
d0utone

Reputation: 300

How to save Zoomed and Panned Canvas to dataUrl in Javascript

I build a canvas Element in which you can zoom and pan a background image and by click you can add Icons on it. It is built on fabric js.

So once I added icons and zoomed and panned, I would like to save the image to dataurl. If I just use canvas.toDataURL, I can only see the currently shown area. Does anybody have an Idea, how I can save the entire area of the background image with all elements on the canvas? I therefore need a function, which resets the zoom and the pan and adjusts the size of the canvas to the size of the background image.

I included an example of how initialized my canvas below.

// New Fabric Canvas
 var canvas = new fabric.Canvas('c'); //render image to this canvas

window.addEventListener('resize', resizeCanvas, false);

  function resizeCanvas() {
    canvas.setHeight(window.innerHeight);
    canvas.setWidth(window.innerWidth);
    canvas.renderAll();
  }

  // resize on init
  resizeCanvas();
        
// Load image
 var image = new Image();
    
    image.onload = function() {
     loadImage(image, canvas);
     canvas.height = image.height;
     canvas.width = image.width;
 }


 function loadImage(image, canv) {
     var img = new fabric.Image(image, {
         selectable: false,
         lockUniScaling: true,
         centeredScaling: true,
         alignX: "mid",
         alignY: "mid",
     });
     canv.add(img);
     canv.centerObject(img);
 }

 image.src = 'http://placehold.it/350x150';
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.1.0/fabric.all.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="canvasarea" style="background: #000;"> 
        <canvas id='c'  onclick="return false;"></canvas>
   </div>

Upvotes: 2

Views: 1852

Answers (1)

user
user

Reputation: 179

If you just want to generate an image and not change the zoom level of canvas, you can pass multiplier parameter to toDataUrl function.

var dataURL = canvas.toDataURL({
  format: 'png',
  multiplier: 2
});

This will generate an image after zooming in 200%.

You can even specify the part of the canvas, you want to generate an image of by using:

var dataURL = canvas.toDataURL({
  format: 'png',
  left: 100,
  top: 100,
  width: 200,
  height: 200
});

Check the details here, toDataUrl function: http://fabricjs.com/docs/fabric.Canvas.html

Upvotes: 2

Related Questions