JSFiddle - React, Tailwind, and code Playground
by Steve Eberhardt
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.5.0/fabric.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.2.30/vue.cjs.js"></script>
<div id="app">
<canvas ref="canvas" id="canvas" style="border: 1px red solid"></canvas>
</div>
Vue
Vue.createApp({
data: () => {
return {
canvas: null,
}
},
methods: {
initFabric: function() {
console.log('ciao')
var canvasEl = this.$refs.canvas;
canvasEl.width = 400;
canvasEl.height = 200;
this.canvas = new fabric.Canvas(canvasEl, {
// isDrawingMode: true,
centeredScaling: true,
backgroundColor: "#fff",
selectionBorderColor: "rgba(255, 255, 255, 0.8)",
selectionColor: "rgba(255, 255, 255, 0.8)",
selectionLineWidth: 2,
borderColor: "gray",
cornerColor: "black",
cornerSize: 12,
transparentCorners: true,
});
this.canvas.on("selection:created", this.handleSelection);
this.canvas.on("selection:updated", this.handleSelection);
this.canvas.on("after:render", this.updateCanvas);
this.canvas.on("object:modified", this.updateCanvas);
this.canvas.on("object:added", this.updateCanvas);
this.canvas.on("object:removed", this.updateCanvas);
this.canvas.on("mouse:wheel", (opt) => {
var delta = opt.e.deltaY;
var zoom = this.canvas.getZoom();
zoom *= 0.999 ** delta;
if (zoom > 20) zoom = 20;
if (zoom < 0.01) zoom = 0.01;
this.canvas.zoomToPoint({
x: opt.e.offsetX,
y: opt.e.offsetY
},
zoom
);
opt.e.preventDefault();
opt.e.stopPropagation();
});
this.$nextTick(() => {
var rect = new fabric.Rect({
left: 100,
top: 50,
fill: "yellow",
width: 200,
height: 100,
stroke: "lightgreen",
strokeWidth: 4,
dirty: true,
});
this.canvas.add(rect);
rect.center();
this.canvas.setActiveObject(rect);
this.canvas.bringToFront(rect);
this.canvas.renderAll();
});
}
},
mounted: function() {
this.initFabric()
}
}).mount('#app')