let canvas = document.querySelector("canvas");
let ctx = canvas.getContext("2d");
let items = [];
function distance(a, b) {
return Math.sqrt((b.x-a.x)**2 + (b.y-a.y)**2);
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let {itemType, start, end} of items) {
ctx.beginPath();
if (itemType == "line") {
ctx.moveTo(start.x, start.y);
ctx.lineTo(end.x, end.y);
} else {
ctx.arc(start.x, start.y, distance(start, end), 0, 2*Math.PI);
}
ctx.stroke();
}
}
function cursorPoint(e) {
return { x: e.clientX - e.target.offsetLeft, y: e.clientY - e.target.offsetTop };
}
canvas.addEventListener("mousedown", function(e) {
let itemType = document.querySelector("[name='shape']:checked").value;
items.push({itemType, start: cursorPoint(e), end: cursorPoint(e)});
draw();
});
canvas.addEventListener("mousemove", function(e) {
if (e.buttons === 0) return;
items[items.length-1].end = cursorPoint(e);
draw();
});
canvas { border: 1px solid }
<canvas></canvas>
<br><input type="radio" name="shape" value="line" checked>Line
<br><input type="radio" name="shape" value="circle">Circle