JSFiddle - React, Tailwind, and code Playground
HTML
<body onload="init()">
<canvas id="myCanvas" width="600" height="550" style="border:1px solid black; position: absolute;"></canvas>
<canvas id="canvas2" width="600" height="550" style="border:1px solid black; position: absolute;"></canvas>
</body>
JavaScript
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var w = canvas.width, h = canvas.height;
var saberimg = new Image();
saberimg.src = "http://orig05.deviantart.net/c273/f/2015/356/1/7/luke_skywalker_s_lightsaber_rotj_pixel_art_by_radiochicken1-d9l124c.png";
var px, py;
var ax = 269, ay = 100;
var sensitivity = 10;
function init()
{
ctx.drawImage(saberimg, ax, ay);
}
function update(ctx, messages, x, y, mkey)
{
// Clear the board and begin translation
ctx.clearRect(0, 0, w, h);
ctx.translate(ax, ay);
// Check for mousemove
if(px+sensitivity < x)
{
ctx.rotate(Math.PI/180);
}
if(px-sensitivity > x)
{
ctx.rotate(Math.PI/(-180));
}
// Check for click
if(mkey == 0)
{
//mkey = 0
ctx.rotate(Math.PI/10);
}
else if(mkey == 1)
{
// mkey = 1
ctx.rotate(Math.PI/(-20));
}
// Draw image back
ctx.translate(-ax, -ay);
ctx.drawImage(saberimg, x-90, y-438);
//clearRect(0,0,w, h);
// special 'pause button'
/*
if(y <= 30)
{
iHaveThePower(ctx);
}
*/
// Store the previous coordinates
px = x;
py = y;
}
function getMousePos(canvas, event)
{
var rect = canvas.getBoundingClientRect();
return {
x: event.clientX - rect.left,
y: event.clientY - rect.top
};
}
var hold;
document.addEventListener('mousemove', function(event)
{
var x, y;
// Null mouse key
mkey = -1;
var mousePos = getMousePos(canvas, event);
x = mousePos.x;
y = mousePos.y;
var message = 'Mouse position: ' + x + ',' + y;
update(ctx, message, x, y, mkey);
});
var mkey;
document.addEventListener('mousedown', function(event)
{
hold = true;
// Get pressed button
mkey = event.button;
var message = mkey + " pressed.";
var x, y;
var mousePos = getMousePos(canvas, event);
x = mousePos.x;
y = mousePos.y;
update(ctx,...