logo
down
shadow

fabric js - Resize complete canvas according to a rectangle added in a canvas in order to achieve cropping


fabric js - Resize complete canvas according to a rectangle added in a canvas in order to achieve cropping

By : tintin tintin
Date : November 14 2020, 04:48 PM
it fixes the issue Finally after doing some research I am able to do that, instead of resizing the canvas I am adding a rectangle object with "cropper" type as mentioned below
code :
var rect = new fabric.Rect({
                    left: 100,
                    top: 100,
                    fill: 'transparent',
                    width: 400,
                    height: 400,
                    strokeDashArray: [5, 5],
                    stroke: 'black',
                    type: 'cropper',
                    lockScalingX: true,
                    lockScalingY: true,
                    lockRotation: true
                });
                canvas.add(rect);
            var i;
            var croppedLeft = 0;
            var croppedTop = 0;
            var canvasJson = canvas.getObjects();
            // Cropping canvas according to cropper rectangle
            if (canvas.getObjects().length > 0) {
                var i;
                for (i = 0; i < canvas.getObjects().length; i++) {
                    if (canvas.getObjects()[i].type == 'cropper') {
                        croppedLeft = canvas.getObjects()[i].left;
                        croppedTop = canvas.getObjects()[i].top;
                        canvas.setHeight(canvas.getObjects()[i].height);
                        canvas.setWidth(canvas.getObjects()[i].width);
                        canvas.getObjects()[i].remove();
                    }
                }
            }
for (i = 0; i < canvasJson.length; i++) {
                canvas.getObjects()[i].left = canvas.getObjects()[i].left - croppedLeft
                canvas.getObjects()[i].top = canvas.getObjects()[i].top - croppedTop
                canvas.renderAll();
            }


Share : facebook icon twitter icon
Resize the canvas with fabric js

Resize the canvas with fabric js


By : jeff chen
Date : March 29 2020, 07:55 AM
like below fixes the issue Previously answered here.
I'm not sure what you've been trying, but
code :
var canvas = document.getElementsByTagName('canvas')[0];
canvas.width  = 800;
canvas.height = 600;
Resize Canvas without Cropping

Resize Canvas without Cropping


By : iftakharalam
Date : March 29 2020, 07:55 AM
Any of those help The results are expected.
Your rectangle is not being cropped, it's being resized.
code :
var canvas = document.getElementById("myCanvas");
canvas.width=100;
canvas.height=100;

// changing the canvas width/height will automatically erase and drawings
// so you must now redraw those drawings.
var img=new Image();
img.onload=function(){
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    canvas.width=100;
    canvas.height=100;
    ctx.drawImage(img,0,0,img.width,img.height,0,0,canvas.width,canvas.height);
}
img.src=canvas.toDataURL();
html5 canvas cropping is incorrect, when margin is added

html5 canvas cropping is incorrect, when margin is added


By : Ricky Wijaya
Date : March 29 2020, 07:55 AM
I wish did fix the issue. Pay attention to mouseup. You try to get correct top and left values for fixed element, but its top and left properties of style calculated by the viewport of browser (not by the top and left of document). This is correct code.
code :
class CanvasCrop {
  constructor(media) {
    let x1 = 0;
    let y1 = 0;
    let x2 = 0;
    let y2 = 0;
    let dragThreshold = 50;

    let mousedown = false;
    let dragging = false;

    const selectionRect = document.getElementById('selectionRect');

    function reCalc() {
      var x3 = Math.min(x1, x2);
      var x4 = Math.max(x1, x2);
      var y3 = Math.min(y1, y2);
      var y4 = Math.max(y1, y2);
      selectionRect.style.left = x3 + 'px';
      selectionRect.style.top = y3 + 'px';
      selectionRect.style.width = x4 - x3 + 'px';
      selectionRect.style.height = y4 - y3 + 'px';
    }

    function cropMedia(media, {
      stretch = 1,
      left = 0,
      top = 0,
      width,
      height 
    } = {}) {
      const croppedCanvas = document.createElement('canvas');

      croppedCanvas.width = width;
      croppedCanvas.height = height;
      const ctx = croppedCanvas.getContext('2d');

      ctx.drawImage(media, left, top, width, height, 0, 0, width * stretch, height * stretch);

      return croppedCanvas;
    }

    media.onmousedown = function(e) {
      mousedown = true;
      selectionRect.hidden = 0;
      x1 = e.clientX;
      y1 = e.clientY;
    };
    onmousemove = function(e) {
      //todo implement isDragging
      if (mousedown) {
        x2 = e.clientX;
        y2 = e.clientY;
        var deltaX = Math.abs(x2 - x1);
        var deltaY = Math.abs(x2 - x1);
        reCalc();
        if (deltaX > dragThreshold || deltaY > dragThreshold) dragging = true;
      }
    };
    onmouseup = (e) => {
      var pic = document.getElementById('pic');
      var offsetTop = pic.offsetTop;
      var offsetLeft = pic.offsetLeft;
      var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
      var scrollLeft = document.body.scrollLeft || document.documentElement.scrollLeft;
      scrollTop -= offsetTop;
      scrollLeft -= offsetLeft;
      selectionRect.hidden = 1;
      mousedown = false;
      if (dragging) {
        dragging = false;

        let croppedCanvas = cropMedia(media, {
          left: parseInt(selectionRect.style.left, 10) + scrollLeft,
          top: parseInt(selectionRect.style.top, 10) + scrollTop,
          width: parseInt(selectionRect.style.width, 10),
          height: parseInt(selectionRect.style.height, 10)
        });
        const preview = document.getElementById('preview');
        preview.innerHTML = '';
        preview.appendChild(croppedCanvas);
      }
    };
  }
}

const cc = new CanvasCrop(document.getElementById('pic'));
Draw circle and rectangle in canvas using Fabric js

Draw circle and rectangle in canvas using Fabric js


By : Kalydrae
Date : March 29 2020, 07:55 AM
Any of those help I'm trying to draw three shapes. Using three separate functions.
code :
function removeEvents(){
 canvas.off('mouse:down');
 canvas.off('mouse:up');
 canvas.off('mouse:move');
}
var canvas = new fabric.Canvas('canvas1', {
  selection: false
});

var line, isDown;


function drawLine() {
  removeEvents();
  canvas.on('mouse:down', function(o) {
    isDown = true;
    var pointer = canvas.getPointer(o.e);
    var points = [pointer.x, pointer.y, pointer.x, pointer.y];
    line = new fabric.Line(points, {
      strokeWidth: 20,
      fill: '#07ff11a3',
      stroke: '#07ff11a3',
      originX: 'center',
      originY: 'center'
    });
    canvas.add(line);
  });
  canvas.on('mouse:move', function(o) {
    if (!isDown) return;
    var pointer = canvas.getPointer(o.e);
    line.set({
      x2: pointer.x,
      y2: pointer.y
    });
    canvas.renderAll();
  });
  canvas.on('mouse:up', function(o) {
    isDown = false;
  });
}

function drawcle() {

  var circle, isDown, origX, origY;
  removeEvents();
  canvas.on('mouse:down', function(o) {
    isDown = true;
    var pointer = canvas.getPointer(o.e);
    origX = pointer.x;
    origY = pointer.y;
    circle = new fabric.Circle({
      left: pointer.x,
      top: pointer.y,
      radius: 1,
      strokeWidth: 2,
      stroke: 'red',
      fill: 'White',
      selectable: false,
      originX: 'center',
      originY: 'center'
    });
    canvas.add(circle);
  });

  canvas.on('mouse:move', function(o) {
    if (!isDown) return;
    var pointer = canvas.getPointer(o.e);
    circle.set({
      radius: Math.abs(origX - pointer.x)
    });
    canvas.renderAll();
  });

  canvas.on('mouse:up', function(o) {
    isDown = false;
  });

}

function drawrec() {
  var rect, isDown, origX, origY;
  removeEvents();
  canvas.on('mouse:down', function(o) {
    isDown = true;
    var pointer = canvas.getPointer(o.e);
    origX = pointer.x;
    origY = pointer.y;
    var pointer = canvas.getPointer(o.e);
    rect = new fabric.Rect({
      left: origX,
      top: origY,
      originX: 'left',
      originY: 'top',
      width: pointer.x - origX,
      height: pointer.y - origY,
      angle: 0,
      fill: 'rgba(255,0,0,0.5)',
      transparentCorners: false
    });
    canvas.add(rect);
  });

  canvas.on('mouse:move', function(o) {
    if (!isDown) return;
    var pointer = canvas.getPointer(o.e);

    if (origX > pointer.x) {
      rect.set({
        left: Math.abs(pointer.x)
      });
    }
    if (origY > pointer.y) {
      rect.set({
        top: Math.abs(pointer.y)
      });
    }

    rect.set({
      width: Math.abs(origX - pointer.x)
    });
    rect.set({
      height: Math.abs(origY - pointer.y)
    });


    canvas.renderAll();
  });

  canvas.on('mouse:up', function(o) {
    isDown = false;
  });
}

function removeEvents(){
 canvas.off('mouse:down');
 canvas.off('mouse:up');
 canvas.off('mouse:move');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.22/fabric.js"></script>
<div class="stamps">
  <div class="set1">

    <a class="thmb" href="#" onclick="drawLine()">Line</a></br>
    <a class="thmb" href="#" onclick="drawcle()">Draw Circle</a></br>
    <a class="thmb" href="#" onclick="drawrec()">Draw Rectangle</a>


  </div>


  <div class="area">
    <div class="col" id="droppable">
      <canvas id="canvas1" width="720" height="560" style="border:1px solid #ccc"></canvas>

    </div>
  </div>
</div>
How to write text inside created rectangle on canvas using fabric.js canvas library

How to write text inside created rectangle on canvas using fabric.js canvas library


By : Kashif Shahzad
Date : September 19 2020, 04:00 PM
it helps some times Avoid layering HTML over an animated canvas
Both the existing answers suggest that you use HTML and add the text over the canvas.
code :
const myTextBox = {text: "Hi World!!", x: 100, y: 20, background: "#08F8"};
boxText(myTextBox);

function boxText({
        c = ctx, 
        text, x, y, 
        font = "arial", 
        size = 32, 
        padding = 4, 
        color = "#FFF", 
        boxStyle = "#000", 
        background = "", 
        lineWidth = 2
    }) {    
    c.font = size + "px " + font;
    c.textAlign = "center";
    c.textBaseline = "middle";
    const width = c.measureText(text).width;
    if (background) {
        c.fillStyle = background;
        c.fillRect(x, y, width + padding * 2, size + padding * 2);
    }
    if (boxStyle) {
        c.strokeStyle = boxStyle;
        c.lineWidth = lineWidth;
        c.strokeRect(
            x - lineWidth / 2, y - lineWidth / 2,
            width + padding * 2 + lineWidth, size + padding * 2 + lineWidth
        );
    }
    c.fillStyle = color;
    c.fillText(text, x + width / 2 +  padding, y + padding + size / 2 + size / 16);
}
requestAnimationFrame(renderLoop);
const ctx = canvas.getContext("2d");

const textA = {text: "Hi World!!", x: 100, y: 20, background: "#08F8"};
const textB = {text: "Example 2", x: 100, y: 80, size: 26, color: "black", background: "#F808"};

function renderLoop(time) {
   ctx.clearRect(0,0,ctx.canvas.width, ctx.canvas.height);
   textA.x = Math.sin(time / 2500) * 150 + 160;
   textB.x = Math.cos(time / 2500) * 150 + 160;
   textB.text = "Time: " + (time / 1000).toFixed(3);
   boxText(textA);
   boxText(textB);
   requestAnimationFrame(renderLoop);
}


function boxText({
        c = ctx, text, x, y, 
        font = "arial", size = 32, color = "#FFF",
        padding = 4, background = "", 
        boxStyle = "#000", lineWidth = 2
    }) {    
    c.font = size + "px " + font;
    c.textAlign = "center";
    c.textBaseline = "middle";
    const width = c.measureText(text).width;
    if (background) {
        c.fillStyle = background;
        c.fillRect(x, y, width + padding * 2, size + padding * 2);
    }
    if (boxStyle) {
        c.strokeStyle = boxStyle;
        c.lineWidth = lineWidth;
        c.strokeRect(
            x - lineWidth / 2, y - lineWidth / 2,
            width + padding * 2 + lineWidth, size + padding * 2 + lineWidth
        );
    }
    c.fillStyle = color;
    c.fillText(text, x + width / 2 +  padding, y + padding + size / 2 + size / 16);
}
<canvas id = "canvas" width=500 height=150></canvas>
Related Posts Related Posts :
  • javascript - explanation request of a behaviour
  • Converting String into date format in JS
  • Choose element Angular
  • Display background grid by using image with CSS
  • Call function from another Controller in another file AngularJS
  • How to change texture in Gera library?
  • When trying to use windows.location.href , the values of $_POST[''] is lost
  • jQuery click action on appended item
  • NodeJS & Socket.IO: Emit a request event and get the response, when/where should I bind the listener?
  • 4-digit form on bootstrap modal
  • Prevent characters like quotation marks from input
  • Sign in option creation using jsp and oracle database
  • use socket.io in my controller with yeoman
  • What happens under the hood to prevent calling a bound method changing the this object?
  • issue with jquery .append function
  • Is it possible to EventHandle every GET request a page makes via Javascript?
  • How to select class with ng-if
  • Cannot communicate with websocket. Autobahn: received HELLO message, and session is not yet established
  • Socket.io - Cannot connect to client
  • Load Accordian Panel on click rather than page load
  • How to register async middleware module within express.js app?
  • JS / Cannot read property 'push' of undefined
  • how to make jquery plugin?
  • MATH reverting rotated coordinates
  • Add an expandable text box to every post
  • What was the rationale behind having the receiver in functions default to the global object?
  • JavaScript chaining many function
  • while loop over takes the each method
  • What are the difference between $(document).bind('ready', function) and $(document).ready(function() {})
  • cut the string in javascript
  • Tool tip not working on text area bootstrap
  • AngularJS: how to activate first non zero item in ngRepeat?
  • Pattern for "column total" of an array of arrays
  • Any selector using * failed in my case
  • Uncaught ReferenceError: app is not defined in Angularjs
  • Unit testing controller which has a $state.go method in controller
  • Use of Meteor-ui-progress-circle (accessing to Template variables created in the HTML)
  • JavaScript: Google maps mapOptions?
  • How do I track Universal Analytics events through Google Tag Manager?
  • Firefox Scrolling Bug When Changing :after Contents
  • Drop down list does not work
  • Display month and year specific datepicker in jquery
  • How to show BAr graph rather than line graph in High Stoch Chart
  • Accessing Angular $Scope in web workers
  • How to convert JavaScript(UnityScript) to C# and implement a low pass filter?
  • Need a logic to implement select button value via onchange event
  • redirect in codeigniter using ajax function
  • How to populate this form data and post it with jquery
  • Retrive value from array id in js function
  • angularjs $index when ng-hide with ng-repeat
  • ExtJS TaskRunner
  • Progress bar not hiding after fetching values via AJAX in JavaScript
  • Pop up window code fails
  • how to make dynamic javascript array with key and value group
  • Implement Facebook API login with reactjs
  • What is the meaning of sign ':' in javascript
  • Change all id's in HTMLDivElement using jQuery
  • load multiple pages from different domain in different divs using javascript
  • Could Not Resolve Host github.com
  • jQuery "Chosen" on-filter event?
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org