简体   繁体   中英

How to clear a specific element of a canvas?

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?

JSFiddle Demo

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>

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 );

};

http://jsfiddle.net/o6a2uot4/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM