SVG Flashlight Visual Effect Tutorial

Create the light for a flashlight with SVG and JavaScript

SVG Flashlight Visual Effect Example Introduction SVG Markup Radial Gradient Ellipse JavaScript Animation Tips Source Code Page Summary

Introduction

Learn to create a light effect with SVG and JavaScript alone. The animated lighting effect with JavaScript and SVG looks like the light of a flashlight searching in the dark. No graphics are required for this article. This tutorial demonstrates how to create an SVG radial gradient, and animate the center of the gradient.

SVG Markup

Declare an SVG element in a Web page. Include the svg namespace in the opening svg tag of the SVG element. The value assigned to the xmlns attribute, points to the SVG specification. The following markup demonstrates declaring the SVG tag. The height and width equal 300. The id equals sv.

<svg 
id="sv" 
height="300" 
width="300" 
xmlns="http://www.w3.org/2000/svg">

Radial Gradient

Declare a defs tag which encloses a radialGradient tag. Set the radialGradient tag's cx,cy,r,fx, and fy attributes.

Attribute cx represents the center of the X position of the radial gradient. The r property sets the size of the radius. Attribute cy represents the center of the Y position of the radial gradient. This article explains how to animate the cx property.

The radialGradient displays a gradient of color radiating outward from colors closest to the origin (center) of the circle outward to the edge of the circle.

The following markup demonstrates how to begin the defining a radial gradient with SVG. The markup declares an id attribute with the value grad. JavaScript accesses the SVG gradient by id, in order to provide animation.

<defs>

<radialGradient 
id="grad" 
cx="50%" 
cy="50%" 
r="30%" 
fx="50%" 
fy="50%"
>
...

</defs>
		

Stop Colors

Declare four stop tags with offset, stop-color, and stop-opacity attributes. The following markup demonstrates the first stop tag.

<stop 
id="stopIn" 
offset="0%" 
style="stop-color:rgb(255,255,255); 
stop-opacity:0" 
/>
		

The offset attribute determines where the color begins to display, based on the origin of the circle. For example, the first stop begins at offset="0%". Therefore the first stop-color starts at the center of the circle. The second stop begins at offset="20%". Therefore the second stop-color begins to display 20% of the distance away from the center of the circle. The following markup demonstrates declaring the attributes for the second stop color.

<stop 
id="stopMid" 
offset="20%" 
style="stop-color:rgb(200,200,255); 
stop-opacity:0.9" 
/>

The stop-colors in this example apply RGB decimal triplets. The triplets represent the color which displays at the assigned offset value, within the radial gradient. For example the first stop-color color equals rgb(255,255,255). The first stop-color displays as pure white at the offset which equals 0%. Therefore the first stop color displays white in the very center of the radial gradient.

The second stop-color equals rgb(200,200,255) representing 200 out of a maximum value of 255 for the red and green channels. However the blue channel displays at the full value of 255. The second offset equals 20% Therefore about one fifth from the origin of the circle a very bright bluish color displays. SVG Flashlight Visual Effect displays a barely noticeable blue tint.

Stop Opacity

The stop-opacity attribute indicates the level of transparency for a stop-color. Values range between 0.0 and 1.0 Values determine how much of the background image shows through the gradient. A value of 0 means the entire background shows through. A value of 1 means none of the background shows through and the full stop color displays.

The first stop color includes an opacity value of 0 therefore the background black color shows through. However stop locations farther from the origin provide gradations toward the white stop color potentially blending with the color.

The second stop color includes an opacity value of 0.9. Most of the very light blue color shows through in a gentle gradation from about one fifth away from the origin of the circle.

The SVG markup declares four complete stop tags. The stop tags create colors which radiate outward becoming more transparent the farther they appear from the center of the circle. However the center of the circle includes a solid dark area. The effect resembles light from a flashlight.

The Ellipse

The def tag includes definitions which describe a radial gradient with a set of stop colors and opacities. Declare an ellipse element below the def element. The url attribute of the ellipse tag assigns the id assigned to the radialGradient previously. That assignment causes the ellipse to fill with the radial gradient we just declared.

The following line of code assigns the grad id to the fill attribute of an SVG element. Remember grad is the id of the radial gradient we just declared. The next step demonstrates declaring the entire SVG ellipse with more attributes, including fill.

fill="url(#grad)" 

The following markup includes all the elements needed to declare the ellipse. The cx and cy attributes declare the X and Y coordinates for the center of the ellipse. The ellipse's origin is (150,150) which is the center of our SVG element. The SVG width and height equal 300. The ellipse's major and minor diameter are equal, making the ellipse a circle. The circle has an X radius of 75 assigned to attribute rx. The circle has a Y radius of 75 assigned to attribute ry.

<ellipse 
id="ellipse" 
cx="150" 
cy="150" 
rx="75" 
ry="75" 
fill="url(#grad)" 
/>     
</svg>
		

Now we're done with the SVG portion of the tutorial and it's onto JavaScript.

JavaScript Animation

The goal is to animate the cx property of the radialGradient only. Obtain a reference to the radialGradient, with the following expression.

grad = document.getElementById(
 "grad"
);
	

Create an Array of values between the range of 0 to 1. Each value in the array named A_CX Array sets the X position of the center of the radial gradient, during animation.

A_CX = 
[
0.31,
0.32,
0.31,
0.34,
0.35,
0.36,
0.4,
0.45,
0.5,
0.55,
0.6,
0.65,
0.72,
0.73,
0.72
];
		

Play the Animation

When the user taps the div element, which encloses the svg tag, call user defined JavaScript function runStartF(). Function runStartF() plays the animation forward. First runStartF() stops the timer if it's active. The timer's active if it's not null. Second runStartF() initializes the frame counter to zero. Third runStartF() initializes a timer which activates function runAnimationF(); every 100 milliseconds. Variable N_TIME equals 100.

The following listing includes the entire runStartF() function.

function runStartF(){
 
 if (timer != null){

  runStop();

 } 
  
 nFrameCount = new Number(0); 

 timer = setInterval(

  function(){
 
   runAnimationF();
  
  },
 
  N_TIME
  
); 
 
}
		

Function runAnimationF() verifies the frame count hasn't exceeded the length of array A_CX. If so then runAnimationF() stops the current animation and initializes a timer to run the animation backward.

Otherwise if the frame count is within bounds, then runAnimationF() assigns the gradient's cx attribute based on an index into the array named A_CX. The following listing demonstrates setting an SVG attribute. Method setAttributeNS() is built into SVG.

grad.setAttributeNS(

null, 

'cx',
 
A_CX[
 nFrameCount
]

);

Play Both Directions

This example animates the light moving left then right three times.

The code includes functions to iterate over the A_CX Array both backward and forward. A loop counter stops the animation after three loops both left and right. See SVG Flashlight Visual Effect Source Code for details.

Tips, Tricks, and Issues

The values at both ends of the A_CX Array move forward then backward again. The goal was to provide just a little bounce effect with some jitter to the animation. Perfectly spaced numbers create a robotic feel to the animation. Usually when someone's navigating with a flashlight the motion's a little uneven.

Summary

This article explained how to create a light effect with SVG and JavaScript alone. The animated lighting effect with JavaScript and SVG looks like the light of a flashlight searching in the dark. No graphics were required for this tutorial. This tutorial demonstrated how to create an SVG radial gradient, and animate the center of the gradient.

See more SVG & HTML5 examples. Have fun and love learning!

More SVG & HTML5 Examples!

WebGL Scenes: Responsive Web Design Screen Shots
Copyright © 2015 Seven Thunder Software. All Rights Reserved.