面料JS适合给定尺寸的图像而无需拉伸

时间:2018-11-30 08:03:07

标签: javascript jquery fabricjs

您好,我正在在线打印应用程序上工作,我们在FabricJS中创建一些设计,然后用户可以编辑那些设计以自己的方式替换文本和图像...一切正常,但是当用户使用时,我们面临着图像替换的问题替换图像,我们希望它适合画布上已经存在的图像,也要保持宽高比。以下是用于替换图像的当前代码,但是如果图像是垂直的,则不适合图像。

o  = activeCanvas.getActiveObject();
fabric.Image.fromURL(src, function(m) {
                var i = m.set({
                id: o.id,
                left: o.left,
                top: o.top,
                width: m.width,
                height: m.height
                });
                i.scaleToWidth(o.getScaledWidth());
                activeCanvas.remove(o);
                activeCanvas.add(i);
                renderAppChange();
                zoomoutIn(1);
                setActiveNew(i);
            });

1 个答案:

答案 0 :(得分:0)

从我的观察中,您希望缩放新图像以适合旧图像的widthheight尺寸中的最小尺寸:

const widthFactor = old.getScaledWidth() / newImg.width
const heightFactor = old.getScaledHeight() / newImg.height
const minFactor = Math.min(widthFactor, heightFactor)
newImg.scale(minFactor)

在这里,scale()将保留宽高比。

和要测试的代码段

const canvas = new fabric.Canvas("c")

const url = "https://via.placeholder.com/100x50"
const url2 = "https://via.placeholder.com/50x100"
const url3 = "https://via.placeholder.com/100x100"

fabric.Image.fromURL(url, (img) => {
  canvas.add(img)
}, {
  left: 0,
  top: 10,
})

fabric.Image.fromURL(url2, (img) => {
  canvas.add(img)
}, {
  left: 120,
  top: 10,
})

fabric.Image.fromURL(url3, (img) => {
  canvas.add(img)
}, {
  left: 200,
  top: 10,
})

function insertAndFit (imageURL) {
  const o = canvas.getActiveObject();
  if (!o) {
    throw new Error('select an object first')
  }
  fabric.Image.fromURL(imageURL, function(m) {
    m.set({
      left: o.left,
      top: o.top
    })
    const widthFactor = o.getScaledWidth() / m.width
    const heightFactor = o.getScaledHeight() / m.height
    const minFactor = Math.min(widthFactor, heightFactor)
    m.scale(minFactor)
    canvas.remove(o)
    canvas.add(m)
  })
}

document.getElementById('b1').onclick = () => {
  insertAndFit("https://via.placeholder.com/100x300")
}

document.getElementById('b2').onclick = () => {
  insertAndFit("https://via.placeholder.com/300x100")
}

document.getElementById('b3').onclick = () => {
  insertAndFit("https://via.placeholder.com/200x200")
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.3.2/fabric.js"></script>
<canvas id='c' width="400" height="200"></canvas>
<button id='b1'>insert 100x300</button>
<button id='b2'>insert 300x100</button>
<button id='b3'>insert 200x200</button>