let isDrawing = false;
let x = 0;
let y = 0;
var endPoint = [];
var startPoint = [];
const element = document.getElementById('drawFigure');
const ctx1 = element.getContext('2d');
element.addEventListener('mousedown', e => {
x = e.offsetX;
y = e.offsetY;
isDrawing = true;
startPoint.push({
x: e.offsetX,
y: e.offsetY
});
});
element.addEventListener('mousemove', e => {
if (isDrawing === false) {
x = e.offsetX;
y = e.offsetY;
console.log( "x" +x , "y" +y);
}
});
window.addEventListener('mouseup', e => {
if (isDrawing === true) {
x = e.offsetX;
y = e.offsetY;
endPoint.push({
x: e.offsetX,
y: e.offsetY,
fillcolor: 'blue'
});
drawLine();
isDrawing = false;
}
});
function drawLine() {
ctx1.beginPath();
ctx1.moveTo(startPoint[0].x,
startPoint[0].y);
var half = endPoint[0].y - startPoint[0].y
var x1 = startPoint[0].x + half
var y1 = startPoint[0].y + half / 2
ctx1.lineTo(x1, y1)
console.log(x1, y1);
ctx1.moveTo(x1, y1)
ctx1.lineTo(endPoint[0].x,
endPoint[0].y);
ctx1.lineTo(startPoint[0].x - half, y1);
ctx1.lineTo(startPoint[0].x,
startPoint[0].y);
ctx1.stroke();
}
//-------------
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.moveTo(75, 75);
ctx.lineTo(135, 25);
ctx.lineTo(195, 75);
ctx.lineTo(135, 125);
ctx.closePath();
ctx.stroke();
canvas {
border: 2px dotted black;
width: 460px;
height: 330px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<canvas id="drawFigure" width="560" height="260"></canvas>
<!---------------->
<h3>Hard Stoke 1/2</h3>
<canvas id="myCanvas"> </canvas>
<!-- --->
</body>
</html>