Fabricjs drawImage 替代方案

Fabricjs drawImage alternative

我正在寻找 fabric.js 库的 drawImage() 替代品,所以我制作了 function:

function drawImage(img,sx,sy,swidth,sheight,x,y,width,height) {
  return new fabric.Image(img, {
    left: x,
    top: y,
    width: width,
    height: height,
    id: "rhino",
    clipTo: function (ctx) {
      ctx.rect(sx,sy,swidth,sheight); 
    }
  });
}
var imgElement = new Image();
imgElement.onload = function() {
  var imgInstance = drawImage(imgElement, 33, 71, 104, 124, 21, 20, 87, 104);
  canvas.add(imgInstance);
}; 
imgElement.src = "https://mdn.mozillademos.org/files/5397/rhino.jpg";

结果需要为:

但是我的自定义函数没有得到任何结果。问题出在哪里?

Codepen: http://codepen.io/anon/pen/RaxRqZ

在这里你可以找到解决办法,

var canvas = ctx = '';
canvas = new fabric.Canvas('canvas');
canvas.selection = false;
ctx = canvas.getContext('2d');

function drawImage(imgPath, x, y, width, height) 
{ 
  fabric.Image.fromURL(imgPath, function(img) {
    img.set({
      left: x,
      top: y, 
      width: width,
      height: height,
      id: "rhino",
      clipTo: function (ctx) {
        ctx.rect(5,5,50,50); 
      }
    });
    canvas.add(img).renderAll().setActiveObject(img);
  });
}
var imgElement = new Image();
imgElement.src = "https://mdn.mozillademos.org/files/5397/rhino.jpg";
imgElement.onload = function() {
  drawImage(imgElement.src, 50, 50, 100, 100);
}

https://codepen.io/mullainathan/pen/wGpzvY

我真的不知道你想要实现什么,但出于性能和复杂性的原因,我不建议使用 clipTo。 在临时 canvas 上绘制您需要的图像部分,然后使用此临时 canvas 作为 fabricJS 图像的来源。

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

function drawImage(img,sx,sy,swidth,sheight,x,y,width,height) {
      var tmpc = document.createElement('canvas');
      tmpc.width = swidth;
      tmpc.height = sheight;
      ctx = tmpc.getContext("2d");
      ctx.drawImage(img,-sx,-sy);
      return new fabric.Image(tmpc, {
        left: x,
        top: y,
        width: width,
        height: height,
        id: "rhino"
      });
    }
    var imgElement = new Image();
    imgElement.onload = function() {
      var imgInstance = drawImage(imgElement, 33, 71, 104, 124, 21, 20, 87, 104);
      canvas.add(imgInstance);
    }; 
    imgElement.src = "https://mdn.mozillademos.org/files/5397/rhino.jpg";
<script src="http://www.deltalink.it/andreab/fabric/fabric.js"></script>
<canvas id="c" width="500", height="500"></canvas>