JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="canvasBg" width="800" height="500"></canvas>
JavaScript
var canvasBg = document.getElementById('canvasBg');
var ctxBg = canvasBg.getContext('2d');
var counter = 0;
var mouse =
{
x: 0,
y: 0
};
var missile = new Missile();
window.addEventListener('load', function()
{
setInterval(loop, 1000/60);
canvasBg.addEventListener('mousemove', function(evt)
{
var m = getMousePos(canvasBg, evt);
mouse.x = m.x;
mouse.y = m.y;
}, false);
}, false);
function Missile()
{
this.x = 300;
this.y = 300;
this.width = 19;
this.height = 7;
}
function loop()
{
var targetX = mouse.x - missile.x;
var targetY = mouse.y - missile.y;
var rotation = Math.atan2(targetY, targetX);
ctxBg.clearRect(0,0,canvasBg.width, canvasBg.height);
missile.draw(rotation);
ctxBg.fillStyle = "hsla(0, 0%, 0%, 0.5)";
ctxBg.font = "bold 12px Helvetica";
ctxBg.fillText("mouse x: " + mouse.x + " ~ mouse y:" + mouse.y + " ~ rotation: " + rotation, 30, 30);
}
Missile.prototype.draw = function(a)
{
ctxBg.save();
ctxBg.translate(this.x + this.width/2, this.y + this.height/2);
ctxBg.rotate(a);
ctxBg.fillStyle = "#008BCC";
ctxBg.fillRect(this.width/2 * -1, this.height/2 * -1, this.width, this.height);
ctxBg.restore();
}
function id(i)
{
return document.getElementById(i);
}
function getMousePos(canvas, evt)
{
var rect = canvas.getBoundingClientRect();
var mouseX = evt.clientX - rect.top;
var mouseY = evt.clientY - rect.left;
return {
x: mouseX,
y: mouseY
};
}