I have the following code:
function up(e) {
if(e.target.id === 'appCanvas') {
// add circle at cursor coords
}
}
canvas {
padding: 0;
margin: auto;
display: block;
width: 80%;
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>
<div>
<canvas id="appCanvas" style="border:5px solid #000000;"></canvas>
</div>
</body>
</html>
This creates a html canvas located in the center of the page with a width and height of 80% of the inner page. However, on the javascript side of things, it is not adding a circle at the exact coordinates, it is rather shifted by 20% of the canvas height and width.
How exactly would I make it so I interact with only the 80% canvas, and create circles exactly on the canvas?
use a click event on the canvas. use clientx and clienty methods from the event to create the circle using the arc function and then display the circle using the stroke/fill function
I got it of w3 schools https://www.w3schools.com/tags/canvas_arc.asp
This is some code I wrote
const canvas = document.querySelector("#appCanvas");
canvas.addEventListener("click", circle);
function circle(e){
var ctx = canvas.getContext('2d');
ctx.arc(e.clientX,e.clientY,2, 0,2*Math.PI);
ctx.stroke();
}