Search code examples
javascripthtml5-canvas

How do you find out (print) a Path2D object?


How do I print out the name of a Path2D object?

var something= new Path2D() and then follows the code for the drawing.

Then I store the variable test in another variable with an if statement.

if (ctx.isPointInPath(test, event.offsetX, event.offsetY)) {

    something = test ...

console.log(something) will give Path2D {}.

console.log(toString(something)) will give [object undefined].

console.log(JSON.stringify(something)) will give {}.

Solution

  • JavaScript does not keep track of variable names like that. That's something you'll need to implement yourself.

    When you create a Path2D object with let test = new Path2D(), the Path2D object is created in a block of memory. test does not 'contain' the object, it's merely a pointer to the object's memory address. When you store test to another variable, like let something = test, the only thing being copied to something is the memory address of the object. The storage is one way only - the actual Path2D object has no way of keeping track of what variables hold its memory address. In that sense, the Path2D object itself doesn't have a name. There are only the names of variables that hold its address.

    You will have to use an additional variable to keep track of the 'name'.

    For example:

    let test = new Path2D()
    let name = 'test'
    
    ...
    
    if (ctx.isPointInPath(test, event.offsetX, event.offsetY)) {
        something = test
        name = 'something'
    }
    
    console.log( name )