Reputation: 73
After some research I saw merely the examples of fitting image to canvas. Is it possible to make it other way around and make an image source for the canvas, so when I load the image, Canvas is basically the loaded image and resized to the image scale and dimensions?
What I need is to draw rectangles over image. Rectangle position and size is important to me in relation to the image.
I am using FabricJS.
Upvotes: 1
Views: 2528
Reputation: 4988
This is easy to do using canvas.setWidth() and canvas.setHeight() as soon as you know the image's dimensions.
const canvas = new fabric.Canvas("c")
const url = "https://via.placeholder.com/200x100"
const imgEl = document.createElement("img")
imgEl.src = url
imgEl.onload = () => {
const img = new fabric.Image(imgEl)
img.set({
left: 50,
top: 50,
scaleX: 2,
scaleY: 1.5
})
canvas.add(img)
canvas.requestRenderAll()
document.querySelector('#b').onclick = () => {
canvas.setWidth(img.getScaledWidth())
canvas.setHeight(img.getScaledHeight())
img.set({
left: 0,
top: 0
})
img.setCoords()
canvas.requestRenderAll()
}
}
#c {
border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.5/fabric.js"></script>
<button id="b">fit canvas to image</button>
<canvas id="c" width="500" height="400"></canvas>
Upvotes: 2