JSFiddle - React, Tailwind, and code Playground
by mmis1000
HTML
<canvas id='main' width='450' height='600'></canvas>
CSS
canvas{
border:1px solid;
}
JavaScript
/**Stage class for handle/wrap all image control*/
var Stage = function Stage(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();
}
Stage.prototype.setSize = function setSize(width, height) {
if (!width || !height) {
this.width = $(this.stage).attr('width');
this.height = $(this.stage).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*/
Common = {};
Common.loadExternalImage = function loadExternalImage (url, onload) {
var externalImage = new Image();
externalImage.crossOrigin = "Anonymous";
...