JSFiddle - React, Tailwind, and code Playground
by mmis1000
HTML
<div id='main_wrap'>
<canvas id='main' width='450' height='600'></canvas>
</div>
<div id='loader_out' class='loader'></div>
<div id='loader_in' class='loader'>now loading...
<br/><span id='current'>? / ?</span>
</div>
CSS
canvas {
border:1px solid;
}
#main_wrap {
margin:0 auto;
text-align:center;
}
#loader_out {
background:rgba(127, 127, 127, 0.8);
position:fixed;
top:0px;
bottom:0px;
left:0px;
right:0px;
}
#loader_in {
position:fixed;
bottom:50%;
left:0px;
right:0px;
text-align:center;
color:white;
}
JavaScript
/**Stage class for handle/wrap all image control*/
var Stage = function Stage(canvas) {
this.canvas = canvas;
this.stage = canvas.getContext('2d');
this.height = 0;
this.width = 0;
this.x = 0;
this.y = 0;
this._init();
};
Stage.prototype._init = function _init() {
this.setSize();
this._reloadPaintArea();
this.clear();
};
Stage.prototype.setSize = function setSize(width, height) {
if (!width || !height) {
this.width = $(this.canvas).attr('width');
this.height = $(this.canvas).attr('height');
} else {
this.width = width;
this.height = height;
}
return true;
};
Stage.prototype.setOrigin = function setOrigin(x, y) {
this.x = x;
this.y = y;
return true;
};
Stage.prototype._reloadPaintArea = function _reloadPaintArea() {
this.stage.setTransform(1, 0, 0, 1, this.x, this.y);
};
Stage.prototype.clear = function clear() {
this.stage.save();
this.stage.setTransform(1, 0, 0, 1, this.x, this.y);
// Will always clear the right space
this.stage.clearRect(0, 0, this.width, this.height);
this.stage.restore();
};
Stage.prototype.drawImage = function drawImage(image, fromX, fromY, toX, toY, width, height, rotate, reWidth, reHeight) {
reWidth = reWidth || width;
reHeight = reHeight || height;
rotate = rotate || 0;
var stage = this.stage;
if (rotate !== 0) {
stage.save();
stage.transform(1, 0, 0, 1, toX + reWidth / 2, toY + reHeight / 2);
stage.rotate(rotate);
stage.transform(1, 0, 0, 1, -(toX + reWidth / 2), -(toY + reHeight / 2));
stage.drawImage(image, fromX, fromY, width, height, toX, toY, reWidth, reHeight);
stage.restore();
} else {
stage.drawImage(image, fromX, fromY, width, height, toX, toY, reWidth, reHeight);
}
};
/**common help method*/
var Common = {};
Common.loadExternalImage = function loadExternalImage(url, onload, onerror) {
var externalImage = new Image();
...