简体   繁体   中英

Add box-shadow to image styling on load with fabric.js

Thanks to @ℊααnd I was able to add stroke styling to images added to the canvas . I'd like to also have a drop shadow on any images added to give them more of a "stacked" look. I've tried adding boxShadow: "5px 5px 20px 0px #888888", and taking queues from the documentation but I'm not having any luck. How would I achieve this? Styling in JS is still totally new to me. Any help would be greatly appreciated. Thanks in advance.

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({
            left: 0,
            top: 0,
            angle: 0,
            border: '#000',
            stroke: '#F0F0F0',
            strokeWidth: 40
        }).scale(0.2);
        canvas.add(oImg).renderAll();
        //var a = canvas.setActiveObject(oImg);
        var dataURL = canvas.toDataURL({
            format: 'png',
            quality: 1
        });
    });
};
reader.readAsDataURL(file);
});

I tried plugging all of my code into the snippet inserter but for some reason it didn't want to run there. I figure the above is what's applicable.

You could simply create a shadow object, like this ...

var shadow = {
    color: '#888888',
    blur: 70,
    offsetX: 45,
    offsetY: 45,
    opacity: 0.8
}

and then, set it for the image object, like so ...

oImg.setShadow(shadow);

ᴅᴇᴍᴏ

 var canvas = new fabric.Canvas('canvas'); 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) { //create shadow var shadow = { color: '#888888', blur: 70, offsetX: 45, offsetY: 45, opacity: 0.8 } var oImg = img.set({ left: 0, top: 0, angle: 0, stroke: '#222', strokeWidth: 40 }).scale(0.2); oImg.setShadow(shadow); //set shadow canvas.add(oImg).renderAll(); var dataURL = canvas.toDataURL({ format: 'png', quality: 1 }); }); }; reader.readAsDataURL(file); }); 
 canvas {border: 1px solid black;} 
 <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="canvas" width="180" height="180"></canvas> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM