JSFiddle - React, Tailwind, and code Playground
by heldersepu
HTML
<link rel="stylesheet" href="https://unpkg.com/jcrop/dist/jcrop.css">
<script src="https://unpkg.com/[email protected]/dist/jcrop.js"></script>
<script src="https://unpkg.com/[email protected]/dist/fabric.js"></script>
<img src="https://images.unsplash.com/photo-1595438337199-d50ba5072c7e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=330&q=80" id="target">
<div id="pdr-drawing-area"></div>
<div class="canvas-container" style="position: relative; user-select: none;">
<canvas id="c1" width="600" height="600" style="border:1px solid #ccc; position: absolute; left: 0px; top: 0px; touch-action: none; user-select: none;"></canvas>
</div>
JavaScript
var data, canvas, center
const image = 'https://images.unsplash.com/photo-1595438337199-d50ba5072c7e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=330&q=80';
function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {
var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
return {
width: srcWidth * ratio,
height: srcHeight * ratio,
aspectratio: ratio
};
}
function cropChange(widget, e) {
const pos = widget.pos;
canvas.clear();
canvas.setBackgroundImage(image, function() {
canvas.backgroundImage && canvas.backgroundImage.scaleToWidth(data.width);
canvas.backgroundImage && canvas.backgroundImage.scaleToHeight(data.height);
//canvas.sendToBack(img);
canvas.renderAll();
});
canvas.add(new fabric.Circle({
radius: 30,
fill: '#f55',
top: pos.y + 2,
left: pos.x + 2
}));
canvas.add(new fabric.Rect({
left: pos.x,
top: pos.y,
fill: 'transparent',
width: (pos.w),
height: (pos.h),
strokeDashArray: [5, 5],
stroke: "black",
selectable: false,
evented: false,
//visible: false
}));
canvas.setHeight(data.height);
canvas.setWidth(data.width);
canvas.renderAll();
}
jQuery(function($) {
canvas = new fabric.Canvas('c1');
center = canvas.getCenter();
var img = new Image();
img.onload = function() {
data = calculateAspectRatioFit(this.width, this.height, '400', '600');
jQuery('#target').attr('width', data.width);
jQuery('#target').attr('height', data.height);
jQuery('#pdr-drawing-area').html("Aspect Ratio: " + data.aspectratio);
const stage = Jcrop.attach('target');
stage.listen('crop.change', cropChange);
},
img.src = image;
});