Reputation:
canvas.getActiveObject().type
returns the type of the currently active element in the canvas.
var type = canvas.getActiveObject().type;
if(type){
console.log(type);
}
But when no element is active, I get TypeError, which of course happens because no element is active so there is nothing to getActiveObject from.
TypeError: canvas.getActiveObject(...) is null
Why can't I assign a variable when the activeObject
is null
?
Same error happens, when I try
var type = '';
if(canvas.getActiveObject().type){
type = canvas.getActiveObject().type
}
Upvotes: 1
Views: 67
Reputation: 45252
canvas.getActiveObject()
is returning null
.
That means that canvas.getActiveObject().type
is the same as null.type
.
Referencing any member of null
will throw an exception.
You can solve this any number of ways
Three lines of code:
let type = '';
if(canvas.getActiveObject()) {
type = canvas.getActiveObject().type;
}
Or a one-liner:
let type = canvas.getActiveObject()
? canvas.getActiveObject().type
: '';
Or a more compact one-liner:
let type = (canvas.getActiveObject() || { type: ''}).type;
Upvotes: 2
Reputation: 41
It looks like you're trying to access the property type
returned by the function getActiveObject()
, but since the function returns null
, accessing the type
property is throwing an error. What you need to do instead is check the return value of getActiveObject()
before trying to access any of its members.
The snippet below, which is based on your code, instead checks that the active object returned is not null before attempting to access the members that reside within it.
var activeObject = canvas.getActiveObject();
if (activeObject) {
console.log(activeObject.type);
}
Upvotes: 1
Reputation: 3405
You can't access a null value like an object, I think you should safely access the value like.
var type = '';
if(canvas.getActiveObject() && canvas.getActiveObject().type){
type = canvas.getActiveObject().type
}
Upvotes: 2