Small tutorial: create a jQuery long shadow plugin yourself

 

Long shadow designs are a variation of flat designs that add shadows to create the illusion of depth and result in a three-dimensional design. In this tutorial, we will create a jQuery plugin that allows us to easily convert flat icons by adding fully customizable long shadow icons.

For more information, please refer to: igeekbar.com

 

Click me to see the renderings

 

In this section of the tutorial, we will introduce the elements of the long shadow design, and we will create a simple jQuery plugin that will let us design these elements. 

 

let's start!

 

What is the long shadow element design?

 

We will separate this element into different parts to compose a complete long shadow design:

 

  • The main element, or elements cast shadows.
  • Shadow lengths are usually long, hence the name of the effect. Shadow length also gives the illusion of depth to the main elements.
  • Shadow direction or angle. In the real world, this depends on the location of the light source. Usually, all shadows cast by a light source have the same direction.
  • Shadow color and opacity. The color of the light source affects the color of the shadows. Also, the stronger the light source, the darker the shadows.

 

These elements are superimposed together to form a 3D stereoscopic effect.

 

 

Create Long Shadow jQuery Plugin

 

To create the jQuery long shadow plugin, we will set up a basic jQuery plugin project structure as follows:

 

  • Create a folder to hold the project files. We can name this folder   long-shadows-jquery-plugin .
  • In the project folder, create an  index.html . This will contain our HTML code.
  • Create a file, call it   jquery.longshadows.js , and place it in the folder. This will contain the JavaScript code for our jQuery plugin.
  • To keep the modules separated, we will also create another JavaScript file in this folder and name it script.js. We'll use the jQuery plugin we just created here.
  • In the project folder, the heart.png icon can be found in the attachment of this tutorial.

Our index.html will contain a basic HTML structure and will also include jQuery and our JavaScript files. We need to include the jQuery library because we will be implementing a jQuery plugin. The index.html file should look like this:

 

<html>
<head>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript" src="jquery.longshadows.js"></script>
    <script type="text/javascript" src="script.js"></script>
</head>
<body>
    <img src="heart.png" id="logo">
</body>
</html>

 

  The jquery.longshadows.js file will contain the jQuery plugin code, and we will implement it as follows:

 


(function($) {
    $.fn.longshadows = function(options) {
        var settings = $.extend({
            //options defaults go here
            ...
        }, options);
        //this applies the plugin to all matching elements
        return this.each(function() {
            //code of the plugin comes here
            ...
        });
    }
})(jQuery);

 

We will call the plugin from the script.js file. The required parameters are:

 

  • shadowColor: The color of the shadow cast by the main element.
  • shadowLength: The length of the shadow.
  • shadowAngle The angle of the shadow.
  • shadowOpacity: The shadow is opaque or transparent.
  • spacing: We need this variable to expand the space around the element where we create the long shadow. In this way, the effect will be more obvious.

 

To create the long shadow, we will use the HTML5 canvas component. We can create an in-memory canvas on which we will draw a copy of the original image element and its shadow. To draw the shadow, we'll simply draw a copy of the image element on top of the other, slightly offset.

 

Copies and offsets are calculated using a simple polar transformation based on the shadowLength and shadowAngle parameters. Additionally, we have to color these copies according to the color of the shadow set by the shadowColor parameter. 

 

Because we're drawing shadows as multiple images of each other, we'll draw them in reverse order from back to front, starting with the shadow furthest from the image element. Then we have to set the opacity of the resulting shadow via the shadowOpacity parameter.

 

After drawing the shadow, we will simply draw the original image.

 

Let's see how this translates to the code in the jquery.longshadows.js file:

 

(function($) {
    $.fn.longshadows = function(options) {
        var settings = $.extend({
            shadowColor: "black",
            shadowLength: 100,
            shadowAngle: 45,
            shadowOpacity: 100,
            spacing: 0
        }, options);
 
        return this.each(function() {
            var img = this;
            img.onload = function() {
 
                var self = this;
                var canvas = document.createElement("canvas");
                var ctx = canvas.getContext("2d");
                canvas.width = self.width + settings.spacing;
                canvas.height = self.height + settings.spacing;
 
                for (var r = settings.shadowLength; r >= 1; r--) {
                    var x = Math.round(r * Math.cos(settings.shadowAngle * Math.PI / 180));
                    var y = Math.round(r * Math.sin(settings.shadowAngle * Math.PI / 180));
 
                    ctx.save();
                    ctx.translate(x + settings.spacing / 2, y + settings.spacing / 2);
                    ctx.drawImage(self, 0, 0);
                    ctx.globalCompositeOperation = 'source-in';
                    ctx.fillStyle = settings.shadowColor;
                    ctx.rect(0, 0, canvas.width, canvas.height);
                    ctx.fill();
                    ctx.restore();
                }
                 
                var tempCanvas = copyCanvas(canvas, settings.shadowOpacity / 100.0);
 
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.drawImage(tempCanvas, 0, 0);
                ctx.drawImage(self, settings.spacing / 2, settings.spacing / 2);
 
                self.onload = null;
                $(self).attr("src", canvas.toDataURL("image/png"));
            };
            img.src = img.src;
        });
    };
})(jQuery);
 
function copyCanvas(canvas, opacity) {
    var canvasDest = document.createElement("canvas");
    canvasDest.width = canvas.width;
    canvasDest.height = canvas.height;
    canvasDest.getContext("2d").globalAlpha = opacity;
    canvasDest.getContext("2d").drawImage(canvas, 0, 0);
    return canvasDest;
}

 

This plugin passes parameters through options. These parameters will be merged with default values ​​and stored in the settings variable. This way we can use the plugin quickly without passing any parameters.

 

  The img variable will hold a reference to the original image element where we applied the effect. We need to listen to the image's onload event to ensure that the image is fully loaded when the effect is applied. Also, it will be noted that there is an img.src = img.src; after the onload. This will trigger the onload function as we are not sure of the order in which the browser loads the images and scripts.

 

Inside the onload handler, we create the in-memory canvas element where we will draw the final result, spaced the same size as the image. Then, starting from the farthest point toward the center, we draw a copy of the image on the canvas using a polar transformation of the offset of the drawn image:

 

var x = Math.round(r * Math.cos(settings.shadowAngle * Math.PI / 180));
var y = Math.round(r * Math.sin(settings.shadowAngle * Math.PI / 180));

 

To draw an image on the canvas, we use the canvas 2D context and call the drawImage() function. This will draw a copy of the image on the canvas, but what we need is a colored version of it. For this, we utilize the canvas compositing operation. In this tutorial, use the source-in with a rectangle filled with shadowColor, which will make a copy of the image the same shape as the original but with shadowColor. 

 

Note that if you have images with multiple colors, the result will all be the same color because we are drawing shadows, which are usually the same color.

 

The for loop is responsible for drawing the shadow; however, it is completely opaque. We want to be able to set the shadow opacity using the shadowOpacity parameter. To do this, we use the copyCanvas() function, which takes a temporary canvas and sets the opacity of the canvas content to the specified value.

 

We must do this when the entire shadow is drawn, otherwise stacking transparent images on top of each other will result in a gradient effect.

 

Let's take a look at the last two lines of the onload handler:

 

self.onload = null;
$(self).attr("src", canvas.toDataURL("image/png"));

 

The first line onload removes the handler from the image. We do this because in the next line, we want to set the src of the image drawn on the canvas to a new image of the original image. If we didn't remove the handler, then we would enter an infinite loop.

 

How to use jQuery long shadow plugin?

 

Now that we've implemented this plugin, let's take a look at how we actually use it and the results it produces. For this, we will use the script.js file, where we will call the plugin we just created.

 

The easiest way to call a plugin is:


$(document).ready(function(){
    $("#logo").longshadows();
});

 

This will instruct the browser to call the longshadows() function when the page has finished loading.

 

Calling such a plugin will use default parameters. Since the results with these default parameters are not very good, let's see how we can change them. Let's call the plugin like this:

 

$(document).ready(function(){
    $("#logo").longshadows({
        spacing:50,
        shadowOpacity:30,
        shadowAngle:30,
        shadowLength:400
    });
});

This results in an image like this:

 

Image obtained from our plugin

Since this plugin is configurable and can be applied to any image, multiple images, and endless combinations of parameter values, imagination is your only limit. If we adjust the HTML like this in index.html:


<html>
<head>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript" src="jquery.longshadows.js"></script>
    <script type="text/javascript" src="script.js"></script>
    <style type="text/css">
        body{
            background:rebeccapurple;
            padding: 0;
            margin:0;
        }
        .text{
            display: inline-block;
            margin-top: 50px;
            width: 400px;
        }
        h1 {
            color:white;
            font-family: sans-serif;
            font-size:46px;
        }
        p{
            color:white;
            font-size:18px;
        }
        #logo{
            vertical-align: top;
        }
    </style>
</head>
<body>
    <img src="heart.png" id="logo">
    <div class="text">
        <h1>Long Shadows jQuery Plugin</h1>
        <p>Long shadow design is a variation of flat design to which shadows are added creating the illusion of depth and resulting in a design that looks 3-dimensional.</p>
    </div>
</body>
</html>

 

Also, if we call the plugin script.js with these parameters:

 

$(document).ready(function(){
    $("img").longshadows({
        spacing:150,
        shadowOpacity:20,
        shadowAngle:160,
        shadowLength:400,
        shadowColor:'#330000'
    });
});

We got this result, which is the perfect website header design:

 

 

Example using long shadow effect:

<html>
<head>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript" src="jquery.longshadows.js"></script>
    <script type="text/javascript" src="script.js"></script>
    <style type="text/css">
         
        .text{
            display: inline-block;
            margin-top: 0px;
            margin-left: 10px;
            width: 400px;
        }
        h1 {
            font-family: sans-serif;
            font-size:36px;
            margin-top: 0;
        }
        p{
            font-size:14px;
        }
        #logo{
            vertical-align: top;
        }
 
         
    </style>
</head>
<body>
    <img style="background-color:#e37e52;" src="tutsplus.png" id="logo">         <
    div class="text">
        <h1>Tuts+</h1
        >
obesity For the purpose of coming to a minimum,
        who of ours should exercise any employment except to take advantage of the
        consequences from it. But the pain in the film is irure to condemn, in the pleasure it wants to
        escape from the pain of being clum in pain, none result. Excepteur are blacks longing for non
        they find, they are at fault who forsake their duties, that is toil soothes the soul.</p>
    </div>    
     
</body>
</html>

 

Congratulations

 

You now have the foundation to create a jQuery plugin that adds long shadows to your icons. You can build on top of this plugin to make it work with text, or combine multiple images and shadow effects.

For more sources, please refer to: http://igeekbar.com/igeekbar/post/328.htm

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326486971&siteId=291194637