JSFiddle - React, Tailwind, and code Playground
HTML
Position: <span id="position"></span><br />
TopLeft: <span id="topLeft"></span><br />
BottomRight: <span id="bottomRight"></span><br />
<input type="button" id="copy" value="COPY" /><br />
<div id="copiedContent"></div>
<canvas id="source" width="300" height="300" style="border: solid 1px #000;"></canvas>
JavaScript
var down = false;
var topLeft;
var bottomRight;
var hasBeenDrawnOn = false;
var canvas = $("#source")[0];
var ctx = canvas.getContext("2d");
ctx.textAlign = "center";
ctx.fillText("DRAW HERE", 150, 150);
$("#source").mousedown(function(){
down = true;
if (!hasBeenDrawnOn){
hasBeenDrawnOn = true;
ctx.clearRect(0, 0, 300, 300);
}
});
$("#source").bind("mouseup mouseout", function(){
down = false;
});
$("#source").mousemove(function(e){
if (down){
var x = e.clientX - this.offsetLeft;
var y = e.clientY - this.offsetTop;
topLeft = updatePoint(topLeft, x, y, function(a, b){ return a < b; });
bottomRight = updatePoint(bottomRight, x, y, function(a, b){ return a > b; });
ctx.fillRect(x, y, 1, 1);
$("#position").text("x: " + x + " - y: " + y);
$("#topLeft").text("x: " + topLeft.x + " - y: " + topLeft.y);
$("#bottomRight").text("x: " + bottomRight.x + " - y: " + bottomRight.y);
}
});
$("#copy").click(function(){
if (!topLeft || !bottomRight) return;
var width = bottomRight.x - topLeft.x;
var height = bottomRight.y - topLeft.y;
var newCanvas = document.createElement("canvas");
newCanvas.width = width;
newCanvas.height = height;
$(newCanvas).css("border", "solid 1px #666");
var imageData = ctx.getImageData(topLeft.x, topLeft.y, width, height);
newCanvas.getContext("2d").putImageData(imageData, 0, 0);
$("#copiedContent").append(newCanvas);
});
function updatePoint(point, x, y, checkFunc){
if (point === undefined) {
point = { x: x, y: y }
} else {
if (checkFunc(x, point.x)) { point.x = x; }
if (checkFunc(y, point.y)) { point.y = y; }
}
return point;
}