Adjusting the shadow on the inserted image

Currently, I am using fabric.js to manipulate images that are added to my canvas. The issue I am facing is with the shadow around the image not being even. The code I have tried so far is displayed below, but you can view what I am aiming for by clicking here. Can someone please help me figure out what mistake I might be making that is causing the shadow to not display correctly?

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: 'rgba(0,0,0,0.6)',
        blur: 20,
        offsetX: 0,
        offsetY: 0,
        opacity: 0.6,
        fillShadow: true,
        strokeShadow: true
      }

      var oImg = img.set({
        left: 0,
        top: 0,
        angle: 0,
        stroke: '#222',
        strokeWidth: 40
      }).scale(0.2);
      oImg.setShadow(shadow); 
      canvas.add(oImg).renderAll();
      var dataURL = canvas.toDataURL({
        format: 'png',
        quality: 1
      });
    });
  };
  reader.readAsDataURL(file);
});

oImg.setShadow(shadow);
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 />
<br>
<canvas id="canvas" width="200" height="200"></canvas>

Answer №1

When an image uploaded is in png format, it will affect the borders differently compared to other image formats. You can utilize the affectStroke property to impact the stroke as well. Check out the documentation for more details.

DEMO

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: 'rgba(0,0,0,0.6)',
        blur: 20,
        offsetX: 20,
        offsetY: 20,
        affectStroke: true
      }

      var oImg = img.set({
        left: 0,
        top: 0,
        stroke: 'black',
        strokeWidth: 10
      }).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 />
<br>
<canvas id="canvas" width="400" height="400"></canvas>

Answer №2

Your shadow can be seen behind the object when displayed. Adjusting offsetX or offsetY will make the shadow visible, as demonstrated below:

var shadow = {
    color: 'rgba(0,0,0,0.6)',
    blur: 20,    
    offsetX: 50,
    offsetY: 50,
    opacity: 0.6,
    fillShadow: true, 
    strokeShadow: true 
}

http://jsfiddle.net/5KKQ2/2565/

An ongoing issue regarding shadow size is documented here, but it has not been resolved yet. Hopefully this information proves helpful.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting up the propTypes for interface in React TypeScript

How can I specify the correct PropTypes for a property that is an interface in TypeScript with PropTypes? Requirements - Implementing both TS and PropTypes. Goal - To have a more precise type definition than PropTypes.any that meets standard eslint an ...

The ElementNotInteractableException was thrown because the element could not be accessed via the keyboard when trying to input text into the FirstName field on Facebook

The issue is as follows: Exception encountered in thread "main" org.openqa.selenium.ElementNotInteractableException: Element is not accessible via keyboard Here is the code snippet: System.setProperty("webdriver.gecko.driver"," ...

Executing an Ajax SPARQL request in Firefox

I've been attempting to run an asynchronous Ajax sparql query on dbpedia using Firefox, but I encountered a strange issue that I can't seem to figure out. Surprisingly, the query works perfectly fine in Chrome, Edge, and Internet Explorer, but wh ...

Navigating AngularJS with multiple external files and folders

Recently dove into Angular and hit a roadblock with routing. I followed the setup instructions, but for some reason it's not functioning as expected. index.html: <!DOCTYPE html> <html lang="en> <head> <meta charset="utf-8> ...

Step-by-Step Guide on Dividing Table Row Data into Two Distinct Tables

At present, I have created a dynamic table that retrieves data from the database using forms in Django. I'm facing an issue with this table as even though there are 7 columns, only 2 of them are visible. However, all 5 hidden columns do contain impor ...

Storing the current date() in JSON format using AngularJS

I am currently working on saving various data, including the current date, in a JSON file stored in LocalStorage. While I have been successful in saving the data, the date is saved in the ISO 8601 format: [{"date":"2014-10-13T17:55:32.953Z"}] This format ...

Retrieve elements from an array based on the value of an object

I have a list of items that resembles the following structure: var entries = [ { sys: {id:"1"}, fields: "article1" }, { sys: {id:"2"}, fields: "place1" }, { sys: {id:"3"}, fields: "offer2" }, { sys: {id:"1"}, fields: "article2" }, { sys: {id:"1" ...

The onclick event in JavaScript is unresponsive on mobile devices

Our website is powered by Opencart 1.5.6.4 and the code snippet below is used to add items to the shopping cart. <input type="button" value="<?php echo $button_cart; ?>" onclick="addToCart('<?php echo $product['product_id']; ?&g ...

When getStaticPaths and getStaticProps are programmed to deliver results

Seeking assistance with my first attempt at using getStaticPaths and getStaticProps in nextJS as a beginner. Can anyone help me resolve this issue? const datas = [ { id: 1, name: "Banheiro", image: "https://res.cl ...

req.body is not defined or contains no data

I am facing an issue with my controllers and routers. bookController.js is functioning perfectly, but when I try to use userControllers for registration and login logic, req.body always appears empty. I tried logging the form data using console.log, but it ...

Managing field placement as the table height grows: tips and tricks

I am encountering an issue with my dynamic form. When I click on the add button, a new row is added to the table. However, once there are more than 6 rows added, the table height starts covering the fields. How can I go about setting this so that the field ...

Exploring the possibilities of reading and writing data in localStorage?

Just starting out with Phonegap, jQuery Mobile, and HTML5 - so please bear with me as I navigate through this learning process! I'm having an issue and could use some help. When trying to use a variable from localStorage, the screen remains blank whe ...

The ngx-treeview is displaying an inaccurate tree structure. Can you pinpoint where the issue lies?

I have structured my JSON data following the format used in ngx-treeview. Here is the JSON file I am working with: [ { "internalDisabled": false, "internalChecked": false, "internalCollapsed": false, "text": "JOURNEY", "value": 1 } ...

Interactive feature on Google Maps information window allowing navigation to page's functions

Working on an Angular2 / Ionic 2 mobile App, I am utilizing the google maps JS API to display markers on a map. Upon clicking a marker, an information window pops up containing text and a button that triggers a function when clicked. If this function simpl ...

The jqueryMobile Dialog persistently opens during pageshow, despite having the cookie already set

My jQuery mobile dialog keeps opening every time the page is refreshed, despite having a cookie set to open it only once. I can't figure out why it's loading without any triggers. Any assistance would be greatly appreciated. JAVASCRIPT function ...

AngularJS allows you to dynamically disable a button based on a value in an array

I have an array containing letters from A to Z and I want to create a list of buttons using them. $scope.alphabet = "abcdefghijklmnopqrstuvwxyz".split(""); I also have another array: $scope.uniqChar = ['a', ' ...

Retrieving all options from a dropdown list in HTML using ASP.net C#

I am currently working with a select list that looks like this: <select name="Section" id="Section" size="5"> <option>Section1</option> <option>Section2</option> <option>Section3</option> <option>Section4< ...

Tips for adding event listeners to dynamically-loaded content using AJAX

I need help with the following code snippet: $("#contantainer").load("some_page.txt"); Inside some_page.txt, I have the following content: <div class="nav"> <ul id="nav_ul"> <li><a class="nav_a" href="#home" id="home"> ...

Unable to adjust the width of the react-select component

I've been struggling to adjust the width of the select element but no matter what I try, it remains at a default width of about 75px. const CustomContainer = styled('div')` width: 100%; height: 100%; display: flex; flex-flow: row wr ...

Back from the depths of the .filter method encased within the .forEach

I have been working on this code and trying to figure it out through trial and error: let _fk = this.selectedIaReportDiscussedTopic$ .map((discussionTopic) => {return discussionTopic.fk_surveyanswer}) .forEach((fk) => { ...