Reputation: 83
How do I use Fabric.js’s canvas.clear
if I only want a certain element to be cleared? My intention is to clear the background once the “delete” button is pressed, but the font to remain. How do I achieve that? They both are added onto the canvas, so if I use canvas.clear
they both are removed.
Do I have to use two canvases?
var canvas = new fabric.Canvas('canvas');
var textObj1 = new fabric.Text('font test', {
left: 100,
top: 350,
fontSize: 30,
fill: "#FF0000" // Set text color to red
});
canvas.add(textObj1);
fabric.Image.fromURL('http://s17.postimg.org/4740ku7z3/i_Stock_000000284123_XSmall.jpg', function(oImg) {
// scale image down, and flip it, before adding it onto canvas
oImg.scale(1);
oImg.selectable = false;
canvas.add(oImg);
});
function deleteimg() {
canvas.clear();
};
<canvas id="canvas" width="800" height="450" style="border:1px solid #000000"></canvas>
<button class="button-big" onclick="deleteimg()">delete</button>
Upvotes: 1
Views: 2503
Reputation: 747
You must repaint everything except the background:
function draw( background ) {
var canvas = new fabric.Canvas( 'canvas' );
canvas.clear();
var textObj1 = new fabric.Text('font test', {
left: 100,
top: 350,
fontSize: 30,
fill: "#FF0000" // Set text color to red
});
canvas.add(textObj1);
if ( background ) {
fabric.Image.fromURL( 'http://s17.postimg.org/4740ku7z3/i_Stock_000000284123_XSmall.jpg', function (oImg) {
// scale image down, and flip it, before adding it onto canvas
oImg.scale(1);
oImg.selectable = false;
canvas.add(oImg);
} );
}
}
// Call function with background
draw( true );
function deleteimg(){
// Call function without background
draw( false );
};
Upvotes: 1