<! DOCTYPEhtml>
<html>
<head>
<meta charset="utf-8">
<title>Canvas click event</title>
</head>
<body>
<canvas id="myCanvas" width="800" height="800" style="border:1px solid #d3d3d3;">Your browser does not support the HTML5 canvas tag.</canvas>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
$(function () {
var myAction = {}, ctx;
var dom = {
canvas: $('#myCanvas')}; $.extend(myAction, {initCanvas: function () {
ctx = dom.canvas[0].getContext("2d");
ctx.rect(10.10.100.100);
ctx.rect(120.10.100.100);
ctx.stroke();
},
getEventPosition: function (ev) {
var x, y;
if (ev.layerX || ev.layerX == 0) {
x = ev.layerX;
y = ev.layerY;
} else if (ev.offsetX || ev.offsetX == 0) { // Opera
x = ev.offsetX;
y = ev.offsetY;
}
return { x: x, y: y };
},
initEvent: function () {
dom.canvas.on('click'.function(e) {
var p = myAction.getEventPosition(e);
if (ctx.isPointInPath(p.x, p.y)) {
console.log(1);
} else {
console.log(2); }}); }});var init = function () { myAction.initCanvas(); myAction.initEvent(); } (); })</script>
</body>
</html>
Copy the code
<! DOCTYPEhtml>
<html>
<head>
<meta charset="utf-8">
<title>Canvas click event</title>
</head>
<body>
<canvas id="myCanvas" width="800" height="800" style="border:1px solid #d3d3d3;">Your browser does not support the HTML5 canvas tag.</canvas>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
$(function() {
var myAction = {},
ctx;
var arr = [
{x: 10.y: 10.width: 100.height: 100},
{x: 120.y: 10.width: 100.height: 100}];var dom = {
canvas: $('#myCanvas')}; $.extend(myAction, {initCanvas: function() {
ctx = dom.canvas[0].getContext("2d");
//ctx = canvas.getContext('2d');
myAction.draw();
},
getEventPosition: function(ev) {
var x, y;
if (ev.layerX || ev.layerX == 0) {
x = ev.layerX;
y = ev.layerY;
} else if (ev.offsetX || ev.offsetX == 0) { // Opera
x = ev.offsetX;
y = ev.offsetY;
}
return { x: x, y: y };
},
draw: function(p) {
var who = [];
ctx.clearRect(0.0, dom.canvas[0].width, dom.canvas[0].height);
arr.forEach(function(v, i) {
ctx.beginPath();
ctx.rect(v.x, v.y, v.width, v.height);
ctx.stroke();
if (p && ctx.isPointInPath(p.x, p.y)) {
// If the event coordinates are passed in, use isPointInPath to determine
// If the current environment overwrites the coordinates, put the current environment index value into the arraywho.push(i); }});// We can find the arR element according to the index value in the array.
return who;
},
initEvent: function() {
dom.canvas.on('click'.function(e) {
var p = myAction.getEventPosition(e);
var result = myAction.draw(p);
console.log(result); }); }});var init = function() { myAction.initCanvas(); myAction.initEvent(); } (); })</script>
</body>
</html>
Copy the code