I am trying to figure out the best way to approach this? on clicking a button an image gets loaded as the background of the fabricjs canvas...
I have another button that saves dataURL to PNG... I am trying to hide the background image before saving...
Right now I have attached an event listener to the background image to hide itself on click of the export button, but the background image does not get hidden before the an image is exported... whats the best way to order event execution?
$("#export-image").click(function() {
canvas.deactivateAll().renderAll();
window.open(canvas.toDataURL('png'));
});
$('.background-img').on('click', function(e) {
var imgURL = "http://placehold.it/350x150";
$.ajax({
url: imgURL,
success: function(result) {
fabric.Image.fromURL(imgURL, function(img) {
$("#export-image").click(function() {
img.setOpacity(0);
canvas.renderAll();
});
img.set({width: canvas.width, height: canvas.height, originX: 'left', originY: 'top'});
canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas));
});
}
});
});
I would approach with a fabricjs event instead a dom event.
How you made it, the function that does the dataURL export is registered before the function that hides the image. Also setting opacity to 0 means that the image is currently rendered just with transparent. A waste of time.
You do not need to call renderAll, before toDataURL that will call it on its own.
I would stay with one click event and i would use fabricjs events:
var bgImage;
function hideBg() {
//i would not use setOpacity, this will make
//it render transparent. wasted time.
//canvas.backgroundImage.setOpacity(0);
bgImage = canvas.backgroundImage;
canvas.backgroundImage = null;
}
function showBg() {
canvas.backgroundImage = bgImage;
}
$("#export-image").click(function() {
canvas.on('before:render', hideBg);
canvas.on('after:render', showBg);
canvas.deactivateAll();
window.open(canvas.toDataURL('png'));
canvas.off('before:render', hideBg);
canvas.off('after:render', showBg);
});
$('.background-img').on('click', function(e) {
var imgURL = "http://placehold.it/350x150";
$.ajax({
url: imgURL,
success: function(result) {
fabric.Image.fromURL(imgURL, function(img) {
img.set({width: canvas.width, height: canvas.height,
originX: 'left', originY: 'top'});
//let's save an handler just in case we mess up order in hide and show.
bgImage = img
canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas));
});
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With