FabricJS image object clipTo shape object issue

断了今生、忘了曾经 提交于 2019-12-04 18:55:42

There is some caching issue with the latest version of FabricJS. To get around that, you need to set objectCaching property to false for the rectangle object.

$(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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!