JSFiddle - React, Tailwind, and code Playground
by dbjdbj
HTML
<canvas id='world'></canvas>
JavaScript
var mouseX=0,
mouseY=0,
canvas = document.getElementById("world"),
context = canvas.getContext("2d"),
width2 = canvas.width/2,
height2 = canvas.height/2 ,
/* needle is a rectangle A,B,C where C is a top point, A is left most point */
needle_width = 40 ,
needle_length = 200 ,
Ax = width2+needle_width,
Bx = width2-needle_width,
arrow_color = "darkred" ;
function mouseMoveHandler(event) {
mouseX = event.clientX;
mouseY = event.clientY;
draw_arrow();
}
/* canvas initial dimension are ignored because the
window can be very dynamic (if in a frame like here )
so this is called manually upon code first execution
*/
function windowResizeHandler() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
width2 = canvas.width/2;
height2 = canvas.height/2;
Ax = width2+needle_width;
Bx = width2-needle_width;
}
function draw_arrow () {
// Clear Screen
context.clearRect(0,0,canvas.width,canvas.height);
// Calculate the angle to the mouse
a = Math.atan2(mouseY-canvas.height/2, mouseX-canvas.width/2);
// Draw a trianlge in the direction of the mouse
context.beginPath();
context.fillStyle = arrow_color ;
context.moveTo(width2+Math.cos(a-0.5)*40, height2+Math.cos(a-0.5)*40);
context.lineTo(width2+Math.cos(a+0.5)*40, height2+Math.cos(a+0.5)*40);
context.lineTo(
width2+Math.cos(a)*needle_length,
height2+Math.sin(a)*needle_length
);
context.fill();
}
document.addEventListener('mousemove', mouseMoveHandler, false);
window.addEventListener('resize', windowResizeHandler, false);
/* must do this to give init size to the canvas etc ... */
windowResizeHandler();
// setInterval(this.loop, 1000 / 30 );