简体   繁体   中英

Fabric JS Events On Canvas Objects

I'm loading a base 64 image into a canvas using the fabric.js API. What I need to be able to do is determine when an object on the canvas gets resized. I can't find any documentation on eventing on objects on a canvas. Is there a way to listen to events on these objects? Listening to resize on canvas or window is not working:

$("canvas").on("resize", function () {
    console.log("Resize occurred"); //not called
});

What you are looking for here is not a resize event on the canvas, which will not trigger unless you resize the canvas element itself is, but a resize event on an object rendered on the canvas. Since you are using fabricjs to render your image you can listen to fabricjs events to get your desired result. Overview of all fabricjs events you can find here . In your case object:scaled would be the event to listen to. The following runnable code snippet illustrates an example:

 const canvas = new fabric.Canvas('canvas', { selection: false }); const imageElement = document.getElementById('image'); const img = new fabric.Image(imageElement, { left: 20, top: 20, scaleX: 1, scaleY: 1 }); canvas.add(img); canvas.on('object:scaled', (options) => { console.log( "Object was scaled, current scaleX:", options.target.scaleX, " and scaleY: ", options.target.scaleX) }); 
 canvas { border: 1px solid #000; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.4.0/fabric.min.js"></script> <canvas id="canvas" width="300" height="200"></canvas> <img style="display: none" id="image" src="https://images.unsplash.com/photo-1507146426996-ef05306b995a?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=200&q=80" /> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM