'Change FabricJS objects position and size when canvas width and height is changed
i'm trying to update fabric js objects position and size when when the canvas box width and height is changed
i have used PDFJS library with fabricjs and added drawing canvas on each pdf page (worked perfectly).
but my problem when i zoom in or out the pdf pages, fabricjs objects starts changing there position. is there any way i can fix this or call an event for fabric js ?
here's what my code looks like:
$(".spread .page").each(function () {
$(this).append(
"<div class='canvasArea'><canvas></canvas></div>"
);
});
$(".canvasArea canvas").each(function () {
let target = $(this).closest(".page").attr("data-page-number");
let bookmarkTarget = $(this).closest(".spread")
$("#bookmark").on('click', function(){
bookmarkTarget.addClass("bookmark")
})
$(this).attr("id", target);
var canvas = new fabric.Canvas(target, {
isDrawingMode:false,
});
function addText(e) {
var customtxt = new fabric.IText('Tap and Type', {
fontFamily: 'sans serif',
fontSize: 20,
fontWeight: 400,
fill: 'red',
fontStyle: 'normal',
top: e.offsetY,
cursorDuration: 500,
left: e.offsetX,
});
canvas.add(customtxt);
customtxt.fill = $("#textmode-color").val();
customtxt.fontSize = $("#text-size").val();
}
function addRect() {
var rect = new fabric.Rect({
left: 100,
top: 50,
fill: 'transparent',
stroke: 'rgb(202 28 28 / 73%)',
strokeWidth: 3,
width: 200,
height: 100,
});
canvas.add(rect);
}
canvas.setWidth($(".page").width());
canvas.setHeight($(".page").height());
$(".tool-button").on("click", function () {
$(".tool-button").removeClass("active");
$(this).addClass("active");
const addRectF = () => {
if ($("#addRect").hasClass("active")) {
canvas.on("mouse:up", function (options) {
if (options.target == null) addRect();
canvas.renderAll();
});
} else {
canvas.off("mouse:up", );
}
}
addRectF();
});
$(".tool-button").on("click", function () {
$(".tool-button").removeClass("active");
$(this).addClass("active");
const addTextF = () => {
if ($("#addText").hasClass("active")) {
canvas.on("mouse:down", function (options) {
if (options.target == null) addText(options.e);
canvas.renderAll()
});
} else {
canvas.off("mouse:down", );
}
}
addTextF();
});
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
