javascript - Fabric js How to set percentage object's position -


i'm using fabric.js , changing canvas size dynamically, need scale canvas objects appropriate objects indents (in percent depending on canvas size) top , left. how can set top , left objects position in percent?

like in css:

top: 32% left: 10%

// set canvas size dynamically resize event  this.canvas.setwidth(size.width);  this.canvas.setheight(size.height);

in opinion should have 2 values in order calculate resize ratio.

initialcanvaswidth , finalcanvaswidth.

by assuming have initialcanvaswidth value in page load. can calculate resize ratio on every resize function this:

          window.onresize = utility.debounce(() => {             const finalcanvaswidth = canvaswrapper.clientwidth             const resizeratio = (finalcanvaswidth / initialcanvaswidth).tofixed(3)              setcanvassizeandposition()             scaleobjectsoncanvas(resizeratio)         }, 250) 

by wrapping canvas div , using new width after resize, can set new canvas width , height (in setcanvassizeandposition function)

    this.canvas.setwidth(newwidth).setheight(newheight) 

i think need store aspect ratio of canvas @ beginning in order calculate newheight value

after setting new canvas size, can continue scaling , positioning objects on canvas (scaleobjectsoncanvas function)

    scaleobjectsoncanvas(resizeratio) {         const objects = canvas.getobjects()         (let = 0; < objects.length; i++) {             objects[i].left = objects[i].left * resizeratio             objects[i].top = objects[i].top * resizeratio             objects[i].scalex = objects[i].scalex * resizeratio             objects[i].scaley = objects[i].scaley * resizeratio         }         this.canvas.renderall()     } 

hope helps.

here's real world working example of responsive canvas/fabric.js usage


Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -