javascript - Creating FabricJS object inside function -
i don't understand problem exactly. it's in oop.
so create own class work canvas through fabricjs, , create method add door (i cupboard). method creates fabric.rect. called method 3 times , got 3 doors (rects), should be. when try select 1 of them canvas returns last one.
look @ example jsfiddle, try select 1 of 2 first doors.
function dveri_kupe(options){ var defaultoptions = { doorwidth: 200, doorheight: 400, doordivisionwidth: 5, totalwidth: 735, totalheight: 500, startoffsettop: 50, startoffsetleft: 50, strokecolor: "#aaa", fillstyle: "#ccc", linewidth: "5" } for(var option in defaultoptions) this[option] = options && options[option]!==undefined ? options[option] : defaultoptions[option]; var this_ = this; this.doorarr = [] canvas = this._canvas = new fabric.canvas(options.canvasid); canvas.on('mouse:down', function(options) { if (options.target) { console.log('object. id = ' + options.target.id + " ", options.target); } }); this.adddoor = function(options){ var doorquan = this.doorarr.length; console.log("door add: id = dver" + doorquan) this.doorarr[doorquan] = new fabric.rect({ left: this.startoffsetleft + this.doorwidth * doorquan, top: this.startoffsettop, fill: this.fillstyle, width: this.doorwidth, height: this.doorheight, strokewidth: this.linewidth, stroke: this.strokecolor, id: "dver" + doorquan }); canvas.add(this.doorarr[doorquan]); return doorquan; } this.tellmeastory = function(){ console.log(canvas) console.log(this.doorarr) } }; var dveri_kupe; window.onload = function(){ dveri_kupe = new dveri_kupe({canvasid : "shkaf"}); var doorquan = 3; for(var = 0; < doorquan; i++){ // console.log(dveri_kupe.adddoor()) dveri_kupe.adddoor() } }
thanks
just small correction:
var defaultoptions = { doorwidth: 200, doorheight: 400, doordivisionwidth: 5, totalwidth: 735, totalheight: 500, startoffsettop: 50, startoffsetleft: 50, strokecolor: "#aaa", fillstyle: "#ccc", linewidth: 5 }
fabric.js expects strokewidth
number , passing string. can check documentation: http://fabricjs.com/docs/fabric.rect.html#strokewidth , updated fiddle: https://jsfiddle.net/w2e17803/2/