anonymoose
anonymoose

Reputation: 1243

Uncaught TypeError: canvas.clear is not a function

I have a canvas set up with fabric.js 1.7.21 and I'm getting this error:

Uncaught TypeError: canvas.clear is not a function
    at clearcan (myapp.js:25)
    at HTMLButtonElement.onclick (index.html:43)

From myapp.js:

function clearcan() {
  var txt;
  if (confirm("Chuck this?") == true) {
    canvas.clear().renderAll();
    newleft = 0;
  }
}

From my index.html:

<button onclick="clearcan();" type="button"></button>

I'm not sure what's going on. What am I missing?

Here's a JSFiddle.

Upvotes: 1

Views: 2083

Answers (3)

Abhishek Ekaanth
Abhishek Ekaanth

Reputation: 2567

The best way for removing all the objects that are present on canvas using fabricJS is

 var objectsInGroup= this.canvas.getObjects().map(function(o) {
  return o.set('active', true);
});
canvas.discardActiveGroup();
objectsInGroup.forEach(function(object) {
canvas.remove(object);
});

Upvotes: 0

Durga
Durga

Reputation: 15604

you were initializing the canvas instance inside a self invoking function so that canvas instance is not available inside your clearcan() function.

Remove that function , it will be on global scope, so you can access it in other functions. Here is updated fiddle

var canvas = this.__canvas = new fabric.Canvas('canvas');
function clearcan() {
  var txt;
  if (confirm("Chuck this?")) {
    canvas.clear().renderAll();
    newleft = 0;
  }
}

Upvotes: 1

Khoi Ngo Nguyen
Khoi Ngo Nguyen

Reputation: 174

In HTML5 Canvas Tutorial - https://www.html5canvastutorials.com/advanced/html5-clear-canvas/ said that:

To clear the HTML5 Canvas, we can use the clearRect() method to clear the canvas bitmap.

So please try with

context.clearRect(0, 0, canvas.width, canvas.height);

Upvotes: 0

Related Questions