javascript - How can I add an image from my computer behind an already set image with Fabric.JS? -
i have image frame transparent inside. set background of canvas css. i'm able add images canvas able add 1 image @ time behind transparent portion of frame. how might accomplish this? thank in advance!
var id = document.getelementbyid('rectangle') && rectangle || document.getelementbyid('anothercanvas') && anothercanvas; var canvas = new fabric.canvas(id); document.getelementbyid('file').addeventlistener("change", function (e) { var file = e.target.files[0]; var reader = new filereader(); reader.onload = function (f) { var data = f.target.result; fabric.image.fromurl(data, function (img) { var oimg = img.set({ width: 125, height: 170 }) canvas.add(oimg).renderall(); var = canvas.setactiveobject(oimg); var dataurl = canvas.todataurl({ format: 'png', quality: 1 }); }); }; reader.readasdataurl(file); });
canvas { border: 1px solid #808080; border-radius: 1px; } #rectangle { background: url(http://i.imgur.com/0mt6ho1.png); background-size: contain; background-repeat: no-repeat; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script> <input type="file" id="file"><br /> <canvas id="rectangle" width="637" height="412"></canvas>
please add fabricjs image object left top properties:
var oimg = img.set({ width: 125, height: 170, left: 430, top: 65 })
to make uploaded image behind shouldn't use background image. should insert regular image without controls. this:
fabric.image.fromurl('http://i.imgur.com/0mt6ho1.png', function (img) { var oimg = img.set({ scalex: 0.2, scaley: 0.2, selectable: false }) canvas.add(oimg).renderall(); });
then when upload image, need make selected, move behind, , deselected:
fabric.image.fromurl(data, function (img) { var oimg = img.set({ width: 125, height: 170, left: 430, top: 65 }) canvas.add(oimg); canvas.setactiveobject(oimg); var image = canvas.getactiveobject(); image.moveto(-1); canvas.discardactiveobject(); canvas.renderall(); });
if select object mouse automatically move object top, when deselect - move again.
check fiddle
Comments
Post a Comment