JSFiddle - React, Tailwind, and code Playground
HTML
Drag the red box around quickly. When the DOM and html5 canvas are not in sync, you will see the red square (DOM) lag behind and reveal the green square (html5 canvas)
<div id="main">
<canvas id="canvas"></canvas>
<div id="overlay"><div id="follower"></div></div>
</div>
CSS
#main {
width: 500px;
height: 500px;
position: relative;
border: 2px solid orange;
}
#canvas {
width: 500px;
height: 500px;
position: absolute;
left: 0px;
top: 0px;
}
#overlay {
width: 500px;
height: 500px;
position: absolute;
left: 0px;
top: 0px;
overflow: hidden;
}
#follower {
position: absolute;
left: 0px;
top: 0px;
width: 40px;
height: 40px;
background-color: #FF0000;
}
JavaScript
var canvas = document.getElementById("canvas");
canvas.width = 500;
canvas.height = 500;
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#00FF00";
var follower = document.getElementById("follower");
var x = 250, y = 250;
var main = document.getElementById("main");
var startX, startY;
main.onmousedown = function(e) {
console.log("start");
startX = e.pageX;
startY = e.pageY;
window.onmousemove = function(e) {
console.log("move");
var pageX = e.pageX;
var pageY = e.pageY;
x += pageX-startX;
y += pageY-startY;
startX = pageX;
startY = pageY;
// update the follower
follower.style.left = x + "px";
follower.style.top = y + "px";
// draw the object
ctx.clearRect(0, 0, 500, 500);
ctx.fillRect(x, y, 40, 40);
}
window.onmouseup = function(e) {
console.log("stop");
window.onmousemove = null;
window.onmouseup = null;
}
}