bensladden/vue-fabric-wrapper

Resizing canvas and zooming content

derberni opened this issue · 2 comments

Hi,

I have the challenge that I want to resize my canvas element to that it always fits the size of its parent div, and that the content is scaled accordingly. The div is resized when the window size changes.

Resizing is not a problem, as the canvas width and height can be bound to data properties of the component and these properties can be updated by an event handler that is registered for the resize event of the window.

However i have not yet understood how to also zoom the content of the canvas. FabricJS has a method for zooming (canvas.setZoom) that I could access using a child component as you have shown for another issue. But to calculate the zoom factor i would need the old and new width/height and I'm not sure how to get these values in the child component.

Or is there a simpler way?

Cheers and thanks,
David

Hi,

I have previously done this by defining a static size for editing. When not in edit mode i wanted to lock the window ratio so as not to distort the canvas elements. Therefore i worked out if it was height or width limited. From this i can then set the zoom and width/height see an extract of the code hope it helps:

<fabric-canvas :id="'processCanvas'" :height="editCanvasHeight" :width="editCanvasWidth" > <set-zoom :zoom="canvasZoom"></set-zoom> </fabric-canvas>
These are the computed variables:

editCanvasRatio() {
return this.editCanvasWidth / this.editCanvasHeight
},
heightLimited() {
const projectedHeight = this.windowWidth / this.editCanvasRatio
return this.windowHeight - this.headerHeight < projectedHeight
},
widthLimited() {
return !this.heightLimited
},
runtimeCanvasWidth() {
return this.widthLimited
? this.windowWidth
: this.windowHeight * this.editCanvasRatio
},
runtimeCanvasHeight() {
return this.heightLimited
? this.windowHeight - this.headerHeight - 24 // 24 is padding
: this.windowWidth / this.editCanvasRatio
},
canvasZoom() {
if (this.editMode) {
return 1
}
return this.runtimeCanvasHeight / this.editCanvasHeight
},
canvasWidth() {
if (this.editMode) {
return this.editCanvasWidth
}
return this.runtimeCanvasWidth
},
canvasHeight() {
if (this.editMode) {
return this.editCanvasHeight
}
return this.runtimeCanvasHeight
}`

Hi Ben,

thanks a lot, especially for the fast answer! I'll give it a try in my application.

David