anonymoose
anonymoose

Reputation: 1243

How to deactivate all when saving canvas as image?

I have a fabricjs canvas with a button to add text to the said canvas and another to save the canvas as an image on my computer. When I have an object selected though when I save, the controls are visible. How can I deactivate the controls when I choose to save the canvas as an image, with an object selected- so that the controls don't persist through to the generated PNG like this?

enter image description here

I've tried adding canvas.deactivateAll(); to different parts of the save function, but it hasn't worked.

var canvas = new fabric.Canvas('c', {
  preserveObjectStacking: true,
  lockUniScaling: true,
  centeredScaling: true
});
canvas.setHeight(412);
canvas.setWidth(637);

// Add Text, Enter Editing Mode and Select All
$('#text').on('click', addtext);

function addtext() {
  var text = new fabric.IText('New text');
  canvas.add(text);
  canvas.setActiveObject(text);
  text.enterEditing();
  text.selectAll();
  canvas.renderAll();
}

// Save as image
function download(url, name) {
  $("<a>")
    .attr({
      href: url,
      download: name
    })[0]
    .click();
}

function save() {
  canvas.deactivateAll().renderAll();
  var canvas = document.getElementById('c');
  var dataURL = canvas.toDataURL();
  var name = 'image';
  download(dataURL, name + ".png");
}
$("#save").click(save);
body {
  padding: 10px;
}

canvas {
  border: 1px solid #dddd;
  margin-top: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.22/fabric.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

<button id="text">
Text
</button>

<button id="save">
Save
</button>

<canvas id='c'></canvas>

Upvotes: 1

Views: 785

Answers (1)

Observer
Observer

Reputation: 3706

Edit 2021 :

FabricJS doesn't support deactivateAll() anymore and is replaced by discardActiveObject()

So the line

canvas.deactivateAll().renderAll();

would be

canvas.discardActiveObject().renderAll();

You were very close. Please change canvas variable name inside save function to some different name as long as you are using canvas for fabricjs canvas (it just for avoiding confusion). Update youe save() function :

function save() {
  canvas.deactivateAll().renderAll();
  var c = document.getElementById('c');
  var dataURL = c.toDataURL();
  var name = 'image';
  download(dataURL, name + ".png");
}

You forgot to render canvas after deactivating your object.

Upvotes: 2

Related Questions