Last active
November 16, 2018 15:42
-
-
Save karbassi/225bd1036d96cfaee53b07c3ca81e01d to your computer and use it in GitHub Desktop.
Canvas Position Detection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<title>Position Detection</title> | |
<style> | |
#canvas { | |
border: 5px solid black; | |
cursor: crosshair; | |
} | |
</style> | |
</head> | |
<body> | |
<canvas id="canvas" width="500" height="500"></canvas> | |
<div id="status"></div> | |
<script src="script.js"></script> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const canvas = document.querySelector("#canvas"); | |
const ctx = canvas.getContext("2d"); | |
const statusElement = document.querySelector("#status"); | |
const shapes = []; | |
const drawSVG = (svg) => { | |
let path = new Path2D(svg); | |
ctx.stroke(path); | |
return path; | |
} | |
let path = drawSVG("M20.5 98.5h159v117h159v-117h141v303h-140v-115h-163v108h-156z"); | |
let shape = { | |
name: "My Shape Name", | |
path: path, | |
}; | |
// Adding new shape object to the array | |
shapes.push(shape); | |
canvas.addEventListener("mousemove", (event) => { | |
let bound = canvas.getBoundingClientRect(); | |
// Mouse X and Y | |
let x = event.pageX - bound.top; | |
let y = event.pageY - bound.left; | |
for (let i = 0; i < shapes.length; i++) { | |
const shape = shapes[i]; | |
if (ctx.isPointInPath(shape.path, x, y)) { | |
statusElement.innerText = "Inside Shape"; | |
} else { | |
statusElement.innerText = "Outside Shape"; | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment