Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Locking Background Image in Fabric.js Viewport Transformations

Tech 1
<canvas id="mainCanvas" width="600" height="600" style="border: 1px solid #ccc;"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/5.2.1/fabric.min.js"></script>
<script>
const cvs = new fabric.Canvas('mainCanvas', {
  backgroundVpt: false  // Prevents background from being affected by viewport transformations
});
</script>

Addding Elemenst

// Load background image
fabric.Image.fromURL('path/to/background.jpg', function(bgImg) {
  cvs.setBackgroundImage(bgImg, cvs.renderAll.bind(cvs));
});

// Create a circle
const circ = new fabric.Circle({
  radius: 30,
  fill: 'yellowgreen',
  left: 60,
  top: 60
});

// Create a square
const sqr = new fabric.Rect({
  width: 60,
  height: 60,
  fill: 'orange',
  left: 100,
  top: 30
});

cvs.add(circ, sqr);

Zoom with Mouce Wheel

cvs.on('mouse:wheel', function(event) {
  const evt = event.e;
  const delta = evt.deltaY;
  let currentZoom = cvs.getZoom();
  let updatedZoom = currentZoom * Math.pow(0.999, delta);
  updatedZoom = Math.min(Math.max(updatedZoom, 0.01), 20);
  cvs.zoomToPoint(
    { x: evt.offsetX, y: evt.offsetY },
    updatedZoom
  );
  evt.preventDefault();
  evt.stopPropagation();
});

Panning the Canvas

cvs.on('mouse:down', function(event) {
  const evt = event.e;
  cvs.isPanning = true;
  cvs.prevX = evt.clientX;
  cvs.prevY = evt.clientY;
});

cvs.on('mouse:move', function(event) {
  if (cvs.isPanning) {
    const evt = event.e;
    const vpt = cvs.viewportTransform;
    vpt[4] += evt.clientX - cvs.prevX;
    vpt[5] += evt.clientY - cvs.prevY;
    cvs.requestRenderAll();
    cvs.prevX = evt.clientX;
    cvs.prevY = evt.clientY;
  }
});

cvs.on('mouse:up', function() {
  cvs.isPanning = false;
});

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.