Saif Alabachi
Saif Alabachi

Reputation: 93

How to draw or get pointer coordinates from HTML canvas when using Apple pencil?

I was working on getting mouse events like mouse down, up, move and drawing on an html canvas using my mouse and my Microsoft surface stylus. Now I want to try this with the ipad pro pencil, and I figure out that when the pencil in the canvas area, the canvas didn't recognize the pencil so I can't do any drawing or events. Is there any specific JavaScript library that I should use or any other solution available to use apple pencil with html canvas?

Upvotes: 1

Views: 3297

Answers (1)

Adam Tindale
Adam Tindale

Reputation: 1249

The Apple Pencil works with touch events, not mouse events in HTML. You can set your canvas to listen for the touch events and then check its touchType for stylus. Then you can get the clientX and clientY from that particular touch to do the drawing.

document.getElementById('mycanvas').addEventListener('touchmove', function(event){
    for(var i = 0; i < event.touches.length; i++){
         if(event.touches[i].touchType === "stylus"){
             console.log("x coordinate: " + event.touches[i].clientX);
             console.log("y coordinate: " + event.touches[i].clientY);
         }
    }
});

See the W3C draft spec for touch events for more specifics. Also, see this related question for getting Apple Pencil touch events.

If you are looking for a library that can allow you to easily move between the Apple Pencil and the Surface Pen you should look at Pressure.js. It is fantastic and very easy to use.

Upvotes: 1

Related Questions