Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatic click event for Paper JS

I'm attempting to fire a vanilla JavaScript MouseEvent that will be received by Paper JS. I have an HTML canvas drawing-canvas that has been paper.setup. Here is my current attempt:

const drawingCanvas = document.getElementById('drawing-canvas');
drawingCanvas.dispatchEvent(new MouseEvent('click', {
    buttons: 1,
    clientX: 1153,
    clientY: 550,
    screenX: 1153,
    screenY: 621,
}));

Firing this from the console does not trigger my Layer mouse events.

Here is my attempt at it in Paper Sketch. I would expect the logging to happen when I run it.

How can I fire a vanilla JS mouse event that Paper JS will receive?

like image 654
Scotty H Avatar asked Nov 06 '22 20:11

Scotty H


1 Answers

I guess that there are several things that prevent your example from working:

  • Paper.js has its own MouseEvent class which might be in conflict with native one when used in PaperScript context (e.g. in sketch.paperjs.org) so you should work in JavaScript directly.
  • Paper.js click detection relies on multiple events firing (mousedown then mouseup with some timing and distance checking) so you should use a simpler event (e.g. mousedown).

The simplest for you is to try to decline your specific case from a working example.
Here is a fiddle giving you a start point.

// Setup Paper.js.
paper.setup('canvas');

// Create an orange rectangle covering all the canvas.
new paper.Path.Rectangle({
    rectangle: paper.view.bounds,
    fillColor: 'orange',
    // On mousedown on this rectangle...
    onMouseDown: function(event) {
        // ...draw a blue circle at event point.
        new paper.Path.Circle({
            center: event.point,
            radius: 30,
            fillColor: 'blue'
        });
    }
});

// On button click...
document.getElementById('button').addEventListener('click', function() {
    // ...trigger a fake mousedown event at point 100,100.
    document.getElementById('canvas').dispatchEvent(new MouseEvent('mousedown', {
        clientX: 100,
        clientY: 100
    }));
});
like image 177
sasensi Avatar answered Nov 14 '22 22:11

sasensi