FabricJS图像对象clipTo形状对象问题

时间:2017-06-25 05:05:28

标签: image object fabricjs shape

为什么这个clipTo方法不能处理最新的fabricjs版本,你可以调整对象容器及其中的图像的大小。您还可以移动容器对象和图像对象。

   var imgInstance = new fabric.Image(img, {
                width: instanceWidth,
                height: instanceHeight,
                top: (canvas.getHeight() / 2 - instanceHeight / 2),
                left: (canvas.getWidth() / 2 - instanceWidth / 2),
                originX: 'left',
                originY: 'top'
            });
            canvas.add(imgInstance);
            imgInstance.clipTo = function(ctx) {
                /* image clipping method doesn't work on latest fabricjs version*/
                ctx.save();
                ctx.setTransform(1, 0, 0, 1, 0, 0);

                clippingRect.render(ctx);

                ctx.restore();
            };

http://jsfiddle.net/efmbrm4v/2/

或者他们的另一种形状对象是图像对象。

1 个答案:

答案 0 :(得分:4)

最新版本的FabricJS存在一些缓存问题。要解决这个问题,您需要为矩形对象设置 objectCaching 属性为false

$(document).ready(function() {
   var imageLoader = document.getElementById('imageLoader');
   imageLoader.addEventListener('change', handleImage, false);
});

var canvas = new fabric.Canvas('myCanvas');

var clippingRect = new fabric.Rect({
   left: 100,
   top: 100,
   width: 100,
   height: 100,
   fill: 'transparent',
   opacity: 1,
   objectCaching: false //<-- set this
});
canvas.add(clippingRect);

function handleImage(e) {
   var reader = new FileReader();
   reader.onload = function(event) {
      var img = new Image();
      img.onload = function() {

         var instanceWidth, instanceHeight;

         instanceWidth = img.width;
         instanceHeight = img.height;

         var imgInstance = new fabric.Image(img, {
            width: instanceWidth,
            height: instanceHeight,
            top: (canvas.getHeight() / 2 - instanceHeight / 2),
            left: (canvas.getWidth() / 2 - instanceWidth / 2),
            originX: 'left',
            originY: 'top'
         });
         canvas.add(imgInstance);
         imgInstance.clipTo = function(ctx) {
            ctx.save();
            ctx.setTransform(1, 0, 0, 1, 0, 0);

            clippingRect.render(ctx);

            ctx.restore();
         };
         canvas.renderAll();
      };
      img.src = event.target.result;
   };
   reader.readAsDataURL(e.target.files[0]);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.13/fabric.min.js"></script>
<canvas id="myCanvas" width="400" height="300" style="border: 1px solid black"></canvas>
<br />
<label>Choose a File:</label>
<br/>
<br />
<input type="file" id="imageLoader" name="imageLoader" />
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>