JSFiddle - React, Tailwind, and code Playground
by aleks_664
HTML
<canvas id="canvas" width="350" height="250" style="background-color:#eee; border: 1px solid #ccc; margin:10px;">
</canvas>
JavaScript
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var w = canvas.width;
var h = canvas.height;
var x = 0;
var y = 0;
var moveX;
var moveY;
var draw = false;
var startX = 0;
var startY = 0;
var line = [];
var arr = [];
canvas.addEventListener("mousedown", function(e){
context.clearRect(0, 0, w, h);
startX = e.pageX - this.offsetLeft;
startY = e.pageY - this.offsetTop;
moveX = startX;
moveY = startY;
draw = true;
context.beginPath();
context.moveTo(startX, startY);
line = [];
line.push({
x: startX,
y: startY
});
});
canvas.addEventListener("mousemove", function(e){
if(draw==true){
x = e.pageX - this.offsetLeft;
y = e.pageY - this.offsetTop;
if (x != moveX && y != moveY) {
moveX = x;
moveY = y;
context.lineTo(moveX, moveY);
context.stroke();
line.push({
x: moveX,
y: moveY
});
}
}
});
canvas.addEventListener("mouseup", function(e){
context.stroke();
context.closePath();
context.fill();
console.log(line);
crossing(line, moveX, moveY),
//
draw = false;
});
function crossing(array, x, y) {
array.pop();
for(var i = 0; i < array.length; i++){
if (array[i].x == x && array[i].y == y) {
console.log('Ecть пересечение');
console.log(x , y);
console.log(array);
} else {
console.log('Нету');
}
}
}