Issue
Take for example an html canvas that is centered in the middle of the page with a width and height smaller than the page itself, so there is a rectangular canvas in the middle (sectioned off by an outline).
How would I make this section of the page, the area contained in this rectangle, the interactable part of the page itself?
I have the following code:
canvas.html
<html>
<head>
<meta charset="utf-8">
<title>Graphs</title>
<link rel="stylesheet" href="index.css">
<script type="module" src="application.js"></script>
</head>
<body>
<canvas id="appCanvas" style="border:1px solid #000000;">
</canvas>
</body>
</html>
index.css
canvas {
padding: 0;
margin: auto;
display: block;
width: 60%;
height: 80%;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
application.js
function resize() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
window.onresize = resize;
resize();
application.js also includes a check for mouseup, that draws a circle at the point where the mouse was clicked.
With the given code, I have as mentioned, a box in the middle, however clicking outside of this box still creates a circle. The circle is still made inside the box, it is just projected inside of it. So clicking the top left of the page adds a circle to the top left of the box, and etc.
How would I make it so only clicking in the box makes the circles appear, that is, no projection is occurring (i.e clicking top left of box creates circle at top left of box)?
Solution
If you add the onmouseup eventHandler directly on the canvas only clicks inside the canvas will be registered.
The mouseup event is fired at an Element when a button on a pointing device (such as a mouse or trackpad) is released while the pointer is located inside it. Element: mouseup event
Otherwise you could look at the target of the mouseup event.
document.body.onmouseup = (e) => {
if(e.target.id === 'appCanvas'){
console.log("clicked canvas with no projection");
}
}
canvas {
padding: 0;
margin: auto;
display: block;
width: 60%;
height: 80%;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
<html>
<head>
<meta charset="utf-8">
<title>Graphs</title>
<link rel="stylesheet" href="index.css">
<script type="module" src="application.js"></script>
</head>
<body>
<canvas id="appCanvas" style="border:1px solid #000000;">
</canvas>
</body>
</html>
Answered By - S. Stumm
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.