# Phil Example

This page is named after my son who wondered if it was possible to have a line point to the mouse even after it left the canvas. This proved to be a challenge. Here are two solutions. Both work if there is a default canvas or `noCanvas()` is specified.

In the sketch at the bottom of this page the blue line has one end point at the CanvasClass mouse. It is updated only when the mouse is over the canvas.

The yellow canvas is default p5.js canvas.

Method 1: (italics) The red line has one end point at a point using event.pageX and event.pageY. It requires two events: mouseMoved which works when no mouse button is pressed and mouseDragged which works when a button is pressed. The event.pageX's and event.pageY's is the top left corner of the web page and remains there even when the page is scrolled. This method does not work with finger touches on a touch screen. (The event.page coordinates are printed to the console.)

Method 2: (bold) The green line is similar to the red line but it uses an event setup in CanvasClass.pjs. To initialize the event one has to set globalMouse to the a canvas and then use gMouseX and gMouseY. Like the other mouse coordinates, the "origin" is the upper left corner of the canvas. As written, the interrupt can only be used on one canvas at a time. This method works with finger touches.

Code for this example:

    let canvas1, canvas2, backgroundColor1;  // CanvasClass
    let mpX, mpY;
    function setup() {
    //  noCanvas();
      createCanvas(100, 100);  // make the hidden canvas visible
      background("yellow");

      canvas1 = createCanvasClass(180, 170);
      canvas1.fill(255, 0, 0);
      canvas1.mouseClicked(clicked);
      backgroundColor1 = "FloralWhite";
      canvas2 = createCanvasClass(150, 200);
      canvas2.stroke(255, 0, 255);
      globalMouse = canvas2;
    }
    function draw() {
      canvas1.background(backgroundColor1);
      canvas1.rect(canvas1.mouseX, canvas1.mouseY, 100 ,80);
      canvas2.background("Khaki");
      canvas2.stroke("blue");
      canvas2.line(canvas2.mouseX, canvas2.mouseY, 75, 100);
      canvas2.stroke("red");
      canvas2.line(mpX, mpY, 100, 125);
      canvas2.stroke("green");
      canvas2.line(gMouseX, gMouseY, 50, 75);
    }
    function clicked() {
      if (backgroundColor1 == "FloralWhite") {
        backgroundColor1 = "LightCyan";
      } else {
        backgroundColor1 = "FloralWhite";
      }
    }

    function mouseMoved(event) {
      // called when the mouse is moved but no button is pressed
      print(" event.page: (" + event.pageX +"," + event.pageY + ")");
      mpX = event.pageX - canvas2.canvas.offsetLeft;
      mpY = event.pageY - canvas2.canvas.offsetTop;
    }

    function mouseDragged(event) {
      // called when the moused is moved and a button is pressed
     listMembers(event);
      mpX = event.pageX - canvas2.canvas.offsetLeft;
      mpY = event.pageY - canvas2.canvas.offsetTop;
    }

James Brink, 8/29/2020