JSFiddle - React, Tailwind, and code Playground

by twobomb three

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();
    		if(crossing(line, moveX, moveY)){
        	canvas.dispatchEvent(new Event("mouseup"))
        }
        line.push({
          x: moveX,
          y: moveY
        });
      }
    }
    
});
canvas.addEventListener("mouseup", function(e){

    context.stroke();
    context.closePath();
    context.fill();
    draw = false;
});

 function crossing(line, x, y) {
    console.log(line)
  	if(line.length >= 3){
    	for(var i = 0; i < line.length-2;i++){	if(intersection(line[i].x,line[i].y,line[i+1].x,line[i+1].y,line[line.length-1].x,line[line.length-1].y,x,y)){
      alert("Пересечение");
      return true;
      }
      }
    }
    return false;
 }
 
 
 function intersection(ax1,ay1,ax2,ay2,bx1,by1,bx2,by2){//Проверка пересечения двух линий
var v1,v2,v3,v4;
v1=(bx2-bx1)*(ay1-by1)-(by2-by1)*(ax1-bx1);
v2=(bx2-bx1)*(ay2-by1)-(by2-by1)*(ax2-bx1);
v3=(ax2-ax1)*(by1-ay1)-(ay2-ay1)*(bx1-ax1);
v4=(ax2-ax1)*(by2-ay1)-(ay2-ay1)*(bx2-ax1);
return (v1*v2<0) && (v3*v4<0);
}