JSFiddle - React, Tailwind, and code Playground
by Marc Geurts
HTML
<canvas id="canvas" width=400 height=400></canvas>
CSS
body {
background-color: white;
}
JavaScript
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var canvasOffset = $("#canvas").offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var startX;
var startY;
var isDown = false;
var cx = canvas.width / 2;
var cy = canvas.height / 2;
var w;
var h;
var r = 0;
var img = new Image();
img.onload = function () {
w = img.width;
h = img.height;
draw();
}
img.src = "https://app.i-visualizer.com/static/images/logo.png";
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height);
drawRotationHandle(true);
drawImage();
}
function drawImage() {
context.save();
context.translate(cx, cy);
context.rotate(r);
context.drawImage(img, 0, 0, img.width, img.height, -w / 2, -h / 2, w, h);
context.restore();
}
function drawRotationHandle(withFill) {
context.save();
context.translate(cx, cy);
context.rotate(r);
context.beginPath();
context.moveTo(0, -1);
context.lineTo(w / 2 + 20, -1);
context.lineTo(w / 2 + 20, -7);
context.lineTo(w / 2 + 30, -7);
context.lineTo(w / 2 + 30, 7);
context.lineTo(w / 2 + 20, 7);
context.lineTo(w / 2 + 20, 1);
context.lineTo(0, 1);
context.closePath();
if (withFill) {
context.fillStyle = '#5e9ac1';
context.fill();
}
context.restore();
}
function handleMouseDown(e) {
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
drawRotationHandle(false);
isDown = context.isPointInPath(mouseX, mouseY);
//console.log(isDown);
}
function handleMouseUp(e) {
isDown = false;
}
function handleMouseOut(e) {
isDown = false;
}
function handleMouseMove(e) {
if (!isDown) {
return;
}
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
var dx = mouseX - cx;
var dy = mouseY - cy;
var angle = Math.atan2(dy, dx);
r = angle;
...