JSFiddle - React, Tailwind, and code Playground
HTML
<button id="carregar">Load Imagem</button>
<button id="giraresq">Rotate to Left</button>
<button id="girardir">Rotate to Right</button>
<button id="zoomIn">+ Zoom</button>
<button id="zoomOut" disabled="true">- Zoom</button>
<button id="moveImage" disabled="true">Press do move imagem with mouse</button>
<hr />
<canvas id="canvas" height="300" width="300" data-girar="0" data-scale="0"></canvas>
<img src="http://www.astrosurf.com/santiago/images/lua11_53.jpg" id="image" width="300" height="300" />
CSS
canvas {
border:1px solid red;
}
img {
display:none;
}
JavaScript
var canvas = document.getElementById('canvas');
var image = document.getElementById('image');
var element = canvas.getContext("2d");
//set delta for zoom and keep track of current zoom
var zoomDelta = 0.1;
var currentScale = 1;
//set delta for rotation and keep of current rotation
var currentAngle = 0;
var startX, startY, isDown = false;
var ix=0, iy=0;
jQuery('#carregar').click(function () {
element.translate(canvas.width / 2, canvas.height / 2);
//the new refactored function common to all steps
drawImage();
jQuery('#canvas').attr('data-girar', 0);
this.disabled = true;
});
jQuery('#giraresq').click(function () {
angleInDegrees = -90;
currentAngle += angleInDegrees;
drawImage();
});
jQuery('#girardir').click(function () {
angleInDegrees = 90;
currentAngle += angleInDegrees;
drawImage();
});
jQuery('#zoomIn').click(function () {
currentScale += zoomDelta;
drawImage();
});
jQuery('#zoomOut').click(function () {
currentScale -= zoomDelta;
drawImage();
});
canvas.onmousedown = function (e) {
var pos = getMousePos(canvas, e);
startX = pos.x; //store current position
startY = pos.y;
isDown = true; //mark that we are in move operation
}
canvas.onmousemove = function (e) {
if (isDown === true) {
var pos = getMousePos(canvas, e);
var x = pos.x;
var y = pos.y;
var dx = x - startX;
var dy = y - startY;
var diffX = (canvas.width * currentScale - image.width) / 2;
var diffY = (canvas.height * currentScale - image.height) / 2;
if (ix + dx < -diffX || ix + dx + image.width > canvas.width * currentScale - diffX) dx =0;
if (iy + dy < -diffY || iy + dy + image.height > canvas.height * currentScale - diffY) dy = 0;
//translate difference from now and start
ix += dx;
iy += dy;
element.translate(dx, dy);
drawImage();
//update start...