JSFiddle - React, Tailwind, and code Playground
by Q4Dizzy
HTML
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.6/fabric.min.js"></script>
<script src="https://raw.githubusercontent.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.2.1/lodash.min.js"></script>
<div class="wrapper">
<div id="block" class="ui-widget-content">
<!--h1>Drag me around</h1-->
</div>
</div>
<canvas id="preview"></canvas>
CSS
.wrapper {
width: 700px;
height: 640px;
position: relative;
outline: 1px solid #000;
margin: 10px auto;
}
#block {
width: 200px;
height: 150px;
}
.canvas-container {
outline: 1px solid #000;
}
JavaScript
var item = {
width: 0,
height: 0,
top: 0,
left: 0
}
$('#block').resizable({
containment: ".wrapper",
minHeight: 150,
minWidth: 200,
create: function(event) {
item.width = event.target.clientWidth;
item.height = event.target.clientHeight;
},
stop: function(event, ui) {
item.width = ui.size.width;
item.height = ui.size.height;
}
}).draggable({
containment: ".wrapper",
create: function(event) {
item.top = event.target.offsetTop;
item.left = event.target.offsetLeft;
},
stop: function(event, ui) {
item.top = ui.position.top;
item.left = ui.position.left;
}
});
var canvas = new fabric.Canvas('preview').setDimensions({
width: 700,
height: 640
});
var clipRect1 = new fabric.Rect({
originX: 'left',
originY: 'top',
left: 0,
top: 0,
width: 200,
height: 200,
fill: 'none',
stroke: 'red',
strokeWidth: 1,
selectable: false
});
clipRect1.set({
clipFor: 'pug'
});
canvas.add(clipRect1);
function degToRad(degrees) {
return degrees * (Math.PI / 180);
}
function findByClipName(name) {
return _(canvas.getObjects()).where({
clipFor: name
}).first()
}
function clipByName(ctx) {
var clipRect = findByClipName(this.clipName);
var scaleXTo1 = (1 / this.scaleX);
var scaleYTo1 = (1 / this.scaleY);
ctx.save();
//ctx.translate(-250,-250);
ctx.rotate(degToRad(this.angle * -1));
ctx.scale(scaleXTo1, scaleYTo1);
ctx.beginPath();
ctx.rect(
clipRect.left - this.left,
clipRect.top - this.top,
clipRect.width,
clipRect.height
);
console.log(ctx)
ctx.closePath();
ctx.restore();
}
function addImg(src) {
fabric.Image.fromURL(src, function(oImg) {
canvas.add(oImg.set({
left: 0,
top: 0,
clipName: 'pug',
clipTo: function(ctx) {
return _.bind(clipByName, oImg)(ctx)
}
})).setActiveObject(oImg);
});
}
addImg('http://fabricjs.com/lib/pug.jpg')