What are the steps to create a shadow effect on a bar chart in ChartJs?

Currently, I am utilizing version 3.9 of chartjs to construct a bar chart. My goal is to incorporate a shadow effect on the bars resembling the image in this link:

https://i.sstatic.net/SGIrO.png

Despite my efforts, I have not been able to locate instructions on how to achieve this in the documentation. Could someone provide assistance, please?

Below are the datasets I am working with:

datasets: [
        {
            label: 'SLP',
            data: [23000, 46000, 40000, 41000, 39000, 25000, 45000, 40500, 41000],
            backgroundColor: gradientBg21,
            borderRadius: 9,
            categoryPercentage: 0.8,
            barPercentage: 0.8
        },
        {
            label: 'AXS',
            data: [19000, 22000, 19000, 42000, 39500, 18000, 22000, 18000, 42000],
            backgroundColor: gradientBg31,
            borderRadius: 9,
            categoryPercentage: 0.8,
            barPercentage: 0.8
        }
    ]

To view my current chart setup, visit this JsFiddle link.

Answer №1

import { Bar } from 'react-chartjs-2';

import {
  BarElement,
  CategoryScale,
  Chart as ChartJS,
  Legend,
  LinearScale,
  Title,
  Tooltip,
  TooltipItem,
} from 'chart.js';

ChartJS.register(CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend);

const shadowPlugin = [{
  id: 'shadow',
  beforeDraw: (chart: ChartJS<'bar', number[], unknown>) => {
    const { ctx } = chart;
    const _fill = ctx.fill;
    ctx.fill = function () {
      ctx.save();
      ctx.shadowColor = 'red';
      //ctx.shadowColor = 'rgba(12,77, 229, 0.2)';
      ctx.shadowBlur = 8;
      ctx.shadowOffsetX = 0;
      ctx.shadowOffsetY = 2;
      _fill.apply(this, arguments as any);
      ctx.restore();
    };
  },
}];

<Bar
  height={(BAR_THICKNESS + 28) * data.length + TICKS_PADDING}
  width={chartRefContainer?.current?.offsetWidth || undefined}
  ref={chartRef}
  options={options}
  data={dataWithGradient}
  plugins={shadowPlugin}
/>

View the outcome here!

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

In AngularJS, modifying the value of a copied variable will result in the corresponding change in the value of the main

I'm facing a peculiar issue. I have an array of objects and I used angular.forEach to update the price key value of each object. However, when I make changes in each object, it also affects the main array object. Take a look at the code snippet below ...

How to target an ID containing a dot using jQuery

My nodes sometimes have a dot in their ID attribute, as shown in this example: <div id="site_someSite.com"></div> When I try to select this element using jQuery with the following code: variable = $('#site_'+user); (where user is &a ...

The list in my "Hamburger" menu isn't loading properly

I have been attempting to add a "Hamburger" style menu to my webpage specifically for the "md" size. Although the hamburger menu displays, clicking on it does not trigger any action. I experimented with removing some classes from certain tags, but most of ...

What steps should I take to configure a test environment specifically for conducting tests with selenium and phantomjs?

I am in the process of setting up my environment for headless testing using Selenium and PhantomJS. Getting PhantomJS Ready: To start, I created a folder named c:/phantomjs and downloaded all the necessary PhantomJS script files into it. Next, I set up a ...

What is the best way to position the header at the top and the footer at the bottom of the page, with the main content in between using

Recently, I started using Bootstrap and incorporated Bootstrap 5.3 into this HTML page. My goal is to align the header at the top, footer at the bottom, and adjust the size of the main content in between. Here's the code I attempted: <!DOCTYPE html ...

When running 'npm run dev', an error occurred after the SizeLimitsPlugin emitted at 98%. The specific dependency that was

I encountered an issue while trying to incorporate Google Maps into my Laravel project and received the following error message after running npm run dev: 98% after emitting SizeLimitsPlugin ERROR Failed to compile with 1 errors 10:52:34 PM This dependen ...

Learn the process of applying distinct CSS classes to various elements within an AJAX response

The client initiates an AJAX call via jQuery. Upon fetching data from the database, I return the response which includes the application of numerous classes and styles to various HTML tags. Unfortunately, this process results in code that appears unsightly ...

Make desktop view the default even when accessing from a mobile device

I have searched through all other similar questions but have not been able to find a solution. I am new to programming and am currently learning CSS. I have created a webpage with the following code: <html> <style> body { p.Welcome { ...

"UIWebView experiences a crash when a long press gesture is performed on a textarea element

Looking to implement a custom keyboard for UIWebView that is entirely based on HTML/JS/CSS for compatibility across multiple devices. To achieve this, I included a notification as shown below: [[NSNotificationCenter defaultCenter] addObserver:self selecto ...

Solving the issue of "_c is not defined" error in Vue functional component

I've been experimenting with creating functional components in Vue using the render method. Here's an example of how I attempted to do this: import Vue from "vue" const { render, staticRenderFns } = Vue.compile(`<div>Hello World</div&g ...

Apply the style when the page loads and remove it when clicked

There is a feature in my code that adds a class when an element with the class .tab is clicked. $(function() { $(".tab").click(function() { $(this).addClass('blueback'); $(".tab").not($(this)).removeClass('bl ...

Positioning 3D objects in Three.js

I am working on a 3D Scene using Three.js with an Earth shape that currently looks like this: https://i.sstatic.net/zXWki.png My goal is to modify it to resemble something like this: https://i.sstatic.net/w4ypV.jpg The coloring, stars, and texture are ...

The container is hugging the edges of the screen a little too closely in Firefox

Using Bootstrap 5.0.2, I've implemented custom CSS with the code snippet below: @media (min-width: 1680px) { .container, .container-fluid { box-sizing: border-box !important; max-width: 1750px; } } When viewing the page on Chrome, every ...

Numerous status buttons with a variety of background colors

There are 3 buttons on the order page: [New Order], [Processing], and [Completed]. When the processing button is clicked, the background of the button should change and the order status will be updated in the database. The [New Order] button will have a ...

Exploring Bootstrap 4: Creating list-inline elements for various screen sizes

Is there a way to align list items on top of each other for a breakpoint <=575px (xs), and align the items next to each other for a breakpoint >575px (sm) using Bootstrap display properties? I found some information on How to display a list inline u ...

When executing JavaScript code, the file remains unchanged and does not alter the URL

I want my form to check a SQL database upon submission and execute a JavaScript file that captures the data into a constant. However, instead of running the JS script on the page as desired, it redirects to a new URL. Is there a way to ensure that the JS ...

Struggling to get the font-weights of the Typography and Button components in the new React with Material-UI to display

In both my previous and most recent React applications, I have the following code snippets: <Typography variant="h6" color="inherit" noWrap > h6. Heading </Typography> <Button type="button" size="large" color="primary" > ...

Having trouble getting my Win and Lose Divs to display in my IF statement within the Card Game

Currently, I am developing a card game where players are presented with a card generated by the computer. The player has to decide whether the next card will be higher, lower, or equal to the current one by clicking corresponding buttons. if ((playerChoic ...

Using mui-datatables to display an array of objects

Seeking help from users of mui-datatables. While it successfully handles data in the form of an array of strings, there is an issue when trying to load an array of objects resulting in the following error: bundle.js:126379 Uncaught (in promise) TypeEr ...

What is the technique to transfer the value from collection_select to the onchange method in Rails?

In my task, I need to extract the selected value from the collection_select drop-down menu and pass it to an onchange function. However, when I access the "name" attribute, the printed value is source[index]. Instead, I want to retrieve the actual value ...