binbin
binbin

Reputation: 131

Fabricjs: how to display only a part of image?

I want to display a part of image on canvas using fabricjs (like sprite and background-position in html, css). By default with fabricjs, it displays from the top, left point of image. But I want to display a part of image not from the top, left point.

example

For example: I want to display the black border part of this picture on canvas.

I don't see any property or function in fabricjs that can do that. Do you have suggestion ? Thank you

Upvotes: 1

Views: 1062

Answers (1)

shkaper
shkaper

Reputation: 5018

Have you tried cropX/cropY? Combine them with setting width and height:

const canvas = new fabric.Canvas('c')
const url = 'https://i.sstatic.net/qVhbV.jpg'
const imgEl = document.createElement('img')
imgEl.src = url
imgEl.onload = () => {
  const img = new fabric.Image(imgEl)
  img.set({
    cropX: 70,
    cropY: 140,
    width: 200,
    height: 150,
  })
  canvas.add(img)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js"></script>
<canvas id="c" width="300" height="200"></canvas>

Upvotes: 1

Related Questions