The isPointInPath() function
Summary: The isPointInPath() can be used to determine if the coordinates that you give it are contained within the current path or not
An example of the
isPointInPath()
function being used to change the pointer
The isPointInPath()
function can be used to determine if the
coordinates that you give it are contained within the current path or not. It
only determines the current path so if you have multiple shapes that you want
to test you will need to replay the paths but
not stroke or fill them (so that they're not drawn on to the canvas) and
then use the isPointInPath()
function each time. The
isPointInPath()
function can be used to determine hits for
complex shapes that involve angles or curves - for example the Funnel chart
and drawing API Marker1 objects use the function to facilitate hit testing.
The function only gives you a true or false as to whether the coordinates that you give it are in the path. So you need to create your own functions to get the mouse coordinates and also take the relevant action should the point that you give it be in the current path.
Arguments to the function
The isPointinPath()
function can take two or three
arguments:
- The path object to check. This argument is optional and if not given the default path is checked.
- The X coordinate
- The Y coordinate
context.isPointInPath(path, x, y)
context.isPointInPath(x, y)
An example
<script> window.onload = function () { var canvas = document.getElementById("cvs"); var context = canvas.getContext('2d'); // Draw something on the canvas context.beginPath(); context.rect(25,25,50,50); context.fill(); // Install a mousemove event listener on to the canvas canvas.onmousemove = function (e) { var canvas = e.target; var context = canvas.getContext('2d'); // This gets the mouse coordinates (relative to the canvas). It uses the RGraph.getMouseXY(event) // function var mouseXY = RGraph.getMouseXY(e); var mouseX = mouseXY[0]; var mouseY = mouseXY[1]; // Because the rect was the last path drawn on to the canvas theres no need to replay it if (context.isPointInPath(mouseX, mouseY)) { canvas.style.cursor = 'pointer'; return; } canvas.style.cursor = 'default'; } } </script>
See also: