Reputation: 1009
I'm using a event handler on a HTML canvas to track the coordinates of where a user clicks, and my idea is to connect coordinates together with a line.
The code below creates an Array and keeps a list of coordinates within the canvas element that the user has clicked on, and also contains logic to draw a line between the currently clicked point and the point that's been previously clicked on.
The problem I'm encountering is that, no matter how many times I click, even though my Array is being populated with coordinates, the lines are not being drawn between the points.
I'm not entirely sure what I am doing wrong, or if there is some re-rendering being done that might be wiping away the drawings I make on the canvas.
var coords = [];
var canvas = document.getElementById('canvas');
canvas.addEventListener('click', function (event) {
var coord = { "x": event.screenX, "y": event.screenY };
document.getElementById("coords").innerText = "{" + coord.x + ", " + coord.y + "}";
coords.push(coord);
var max = coords.length - 1;
if (typeof coords[max - 1] !== "undefined") {
var curr = coords[max], prev = coords[max - 1];
var context = canvas.getContext("2d");
context.beginPath();
context.moveTo(prev.x, prev.y);
context.lineTo(curr.x, curr.y);
context.stroke();
}
});
<!doctype html>
</html>
<head>
<title>Drawing canvas</title>
<style>
canvas {
width: 200px;
height: 200px;
border: 2px solid black;
border-radius: 5px;
}
</style>
</head>
<body>
<p id='coords'></p>
<canvas id='canvas'></canvas>
</body>
</html>
Upvotes: 1
Views: 5187
Reputation: 3706
Move your context outside the click event and use canvas coordinates instead of screen one: event.x
and event.y
Do not use CSS dimensions for the canvas. Check this post
var coords = [];
var canvas = document.getElementById('canvas');
var context = canvas.getContext("2d");
canvas.addEventListener('click', function (event) {
var coord = { "x": event.x, "y": event.y};
document.getElementById("coords").innerText = "{" + coord.x + ", " + coord.y + "}";
coords.push(coord);
var max = coords.length - 1;
if (typeof coords[max - 1] !== "undefined") {
var curr = coords[max], prev = coords[max - 1];
context.beginPath();
context.moveTo(prev.x, prev.y);
context.lineTo(curr.x, curr.y);
context.stroke();
}
});
<style>
canvas {
border: 1px solid black;
border-radius: 0px;
}
body {
margin: 0;
padding: 0;
}
</style>
<canvas id='canvas' width="200" height="200"></canvas>
<p id='coords'></p>
Upvotes: 3