fabric.js裁剪图片对象 / Cropping Image Object with fabric.js




Scroll down for english version

最近手上的一个项目使用fabric.js构建一个图片编辑器,裁剪图片是需求之一。虽然fabric.js提供了原生的裁剪功能,但是内置的裁剪功能目的在于将一个图片裁剪成特定的形状而边框不变(如下图),准确的说,这是一个遮罩,而不是裁剪。Google上能搜到的JSFiddle上几乎也都是使用的同样的方法,例如https://fiddle.jshell.net/filiperoberto/wLub3jau/,因此不符合我的需求。

所以我使用了一个曲线救国的方法,大致流程是用户在画布上选中一个图片,点击框选裁剪区域按钮后会在画布上生成一个与图片一样大小的半透明矩形,用户拖拽这个矩形来框选裁剪图片的范围。
当用户点下裁剪按钮后,fabric.js将整个画布导出为base64,并导入进另一张画布中。在另一张画布中根据半透明矩形的大小和缩放比例,对画布进行移动和裁剪。完成后将裁剪后的画布导出并导入进原画布中。

English version

A recent project uses fabric.js to build an image editor, and cropping images is one of the requirements. Although fabric.js provides cropping functionality, the purpose of the built-in cropping functionality is to crop an image to a specific shape, and leaving the frame unchanged. To be precise, this is masking, instead of cropping. The examples found on Google also uses the same approach. For example: https://fiddle. jshell.net/filiperoberto/wLub3jau/, so it doesn’t meet my expectation.

I worked out a workaround, the user selects an image on the canvas, clicks on the “select cropping area” button will generate a semi-transparent rectangle on the canvas with the same size as the image, and the user drags and resizes this rectangle to select the scope of the cropped image.

When the user clicks the crop button, fabric.js exports the entire canvas to base64 and imports it into another canvas. In the other canvas, the canvas is moved and cropped according to the size and scaling of the translucent rectangle. When finished, the cropped canvas is exported and imported into the original canvas.

代码/Source Code

https://github.com/frankgx97/fabricjs-crop/

Demo

https://frankgx97.github.io/fabricjs-crop/index.html




Posted

in

by

Comments

3 responses to “fabric.js裁剪图片对象 / Cropping Image Object with fabric.js”

  1. yang Avatar
    yang

    可以不规则的裁剪图片么?比如说裁剪一个五角星的图片

    1. Frank Avatar

      按照本文这个思路的话应该是不行的

  2. themebetter Avatar

    猫,看着很不错。

发表回复/Leave a Reply

您的电子邮箱地址不会被公开。/Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.