JSFiddle - React, Tailwind, and code Playground
by Tjacke
HTML
<canvas width="200" height="100" id="moveIt">
Your browser does not support canvas.
</canvas>
<form>
<input type ="text" id="mx" /> Mus X<br />
<input type="text" id="my" /> Mus Y<br />
<input type="text" id="name" /> Name<br />
<input type="text" id="cl_x" /> Canvas Klick Pos-x<br />
<input type="text" id="cl_y" /> Canvas Klick Pos-y<br />
<input type="text" id="doc_x" /> Document Klick Pos-x<br />
<input type="text" id="doc_y" /> Document Klick Pos-y<br />
</form>
CSS
canvas{
margin: 10px 0 10px 50px;
background: red;
}
JavaScript
var canvasEl = document.getElementById('moveIt');
canvasEl.addEventListener("mouseover", startCanvas, false);
canvasEl.addEventListener("mouseout", stopCan, false);
function startCanvas(){
document.removeEventListener('mousemove', trackDoc, false); // Remove EventListener
document.removeEventListener('mousedown', docPos, false); // Remove mouseDown Document
canvasEl.addEventListener('mousemove', trackCanvas);
console.log('Track Canvas');
}
function trackCanvas(e){
var _x = 0;
var _y = 0;
_x += canvasEl.offsetLeft - canvasEl.scrollLeft;
_y += canvasEl.offsetTop - canvasEl.scrollTop;
document.getElementById("mx").value = e.clientX - _x;
document.getElementById("my").value = e.clientY - _y;
document.getElementById("name").value = 'Track Canvas';
}
function stopCan(){
canvasEl.removeEventListener('mousemove', trackCanvas, false); // Remove EventListener
document.addEventListener('mousedown', docPos, false); // Start Listener mouseDown Document
document.addEventListener('mousemove', trackDoc, false);
console.log('Track Document');
}
function trackDoc(e){
document.getElementById("mx").value = e.clientX;
document.getElementById("my").value = e.clientY;
document.getElementById("name").value = 'Track Document';
}
// Click Button on Document
function docPos(e){
if(e.button === 0){
document.getElementById("doc_x").value = e.clientX;
document.getElementById("doc_y").value = e.clientY;
console.log('Left click');
}
}
// Click button on Canvas
document.getElementById('moveIt').addEventListener('mousedown', function(e){
if(e.button === 0){
var _x = 0;
var _y = 0;
_x += canvasEl.offsetLeft - canvasEl.scrollLeft;
_y += canvasEl.offsetTop - canvasEl.scrollTop;
document.getElementById("cl_x").value = e.clientX - _x;
...