JSFiddle - React, Tailwind, and code Playground
HTML
<script src="//code.highcharts.com/highcharts.js"></script>
<div id="main-container">
<canvas id="myCanvas" width="500" height="500"></canvas>
<div id="container"></div>
</div>
CSS
#main-container {
width: 500px;
height: 500px;
position: relative;
}
#container {
width: 100%;
height: 100%;
position: absolute;
}
canvas {
border: 1px solid black;
width: 100%;
height: 100%;
position: absolute;
z-index: 10;
}
JavaScript
// HighCharts
// https://jsfiddle.net/BlackLabel/gp741xvf/
// Get the canvas element and its 2D rendering context
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// Variables to track mouse movement
let isMouseDown = false;
let startPoint = {};
let previousPoint = {};
let lassoPoints = [];
// Add event listeners for mouse down, up, and move events
canvas.addEventListener('mousedown', handleMouseDown);
canvas.addEventListener('mouseup', handleMouseUp);
canvas.addEventListener('mousemove', handleMouseMove);
// Function to handle mouse down event
function handleMouseDown(event) {
isMouseDown = true;
startPoint = {
x: event.clientX - canvas.offsetLeft,
y: event.clientY - canvas.offsetTop
};
previousPoint = startPoint;
}
// Function to handle mouse up event
function handleMouseUp(event) {
isMouseDown = false;
const x = event.clientX - canvas.offsetLeft;
const y = event.clientY - canvas.offsetTop;
ctx.strokeStyle = 'red';
ctx.lineWidth = 2;
ctx.moveTo(x, y);
ctx.lineTo(startPoint.x, startPoint.y);
// ctx.strokeRect(startPoint.x, startPoint.y, x - startPoint.x, y - startPoint.y);
ctx.stroke();
selectPointsInLasso();
}
// Function to handle mouse move event
function handleMouseMove(event) {
if (isMouseDown) {
var currentPoint = {
x: event.clientX - canvas.offsetLeft,
y: event.clientY - canvas.offsetTop
};
// Clear the canvas
// ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw the selection rectangle
ctx.strokeStyle = 'red';
ctx.lineWidth = 2;
ctx.moveTo(previousPoint.x, previousPoint.y);
ctx.lineTo(currentPoint.x, currentPoint.y);
// ctx.strokeRect(startPoint.x, startPoint.y, x - startPoint.x, y - startPoint.y);
ctx.stroke();
//console.log(`startPoint = ${JSON.stringify(startPoint)}`);
//console.log(`previousPoint = ${JSON.stringify(previousPoint)}`);
//console.log(`currentPoint =...