Just entered the company to arrange a project, need a picture annotation system (refer to huawei cloud annotation), found fabricJS more suitable for the current business

👍👍👍 currently writing code is relatively smooth, there is no pit, very mysterious problems

Attach a picture

Used in Vue

Fabric Canvas(‘EL’) is a fabric canvas object that can be created by calling const canvas = new fabric.canvas (‘EL’) after the component is rendered

Need to deal with

1. Interactively draw rectangles

General idea: Click on the canvas and trigger the Mouse: Down event to obtain absolutePointer of the canvas. Then trigger the Mouse: Move event to continuously create (New Fabric.rect) objects for interaction. Finally, releasing the mouse triggers the Mouse: Up event to finalize the rectangle

Ps: The canvas is not optional

2. Drag and zoom

Drag: Paste a few key lines of code to execute the mouse: Move event

if(! options.target || ! options.target.selectable) {const delta = new fabric.Point(options.e.movementX, options.e.movementY);
   content.relativePan(delta);
}
Copy the code

Zoom: You need to listen for scroll events in the Canvas container and block native events

ZoomToPoint zoomToPoint zoomToPoint zoomToPoint zoomToPoint

functionZoomToPoint ({pageX = 0, pageY = 0, deltaY, zoom_size = 0.02})letzoom = (deltaY < 0 ? zoom_size : -zoom_size) + this.content.getZoom(); // getZoom current zoom zoom = math. Max (0.1, zoom); // limit the minimum zoom = math. min(2, zoom); // Limit Max const zoomPoint = new Fabric.point (pageX, pageY); this.content.zoomToPoint(zoomPoint, zoom); }Copy the code

3, determine whether the selection is in the picture (simple judgment)

// Verify the rectangle pointfunctionValidation ({x, y}) {const iw = this.iw; // Image high const ih = this.ih;if (x >= 0 && x <= iw) {
      if (y >= 0 && y <= ih) {
        return true; }}return false;
}
Copy the code

4. Data synchronization

Ps: My current handling method may not be very good. Fortunately, the logic is simple, but the project is not demanding at present.

After triggering the data of adding, deleting and modifying a selection, the canvas will be rendered again

Problems encountered

  1. [Bug Mc-10862] – Borders don’t hold after drag changes (currently a bad fix)
content.on('object:scaling', (e) => {
  const o = e.target;
  if(! o.strokeWidthUnscaled && o.strokeWidth) { o.strokeWidthUnscaled = o.strokeWidth; }if(o.strokeWidthUnscaled) { o.strokeWidth = o.strokeWidthUnscaled / Math.max(o.scaleX, o.scaleY); }});Copy the code
  1. Select stretch fixed ratio
const content = this.content = new fabric.Canvas(canvasId, {
  uniScaleTransform: true// Unfixed scale, size following the mouse});Copy the code