Hi guys! In this article, we will design basic traffic lights to understand HTML SVG and javascript library D3JS in more details.
If you don't know about D3JS JavaScript library then I'm going to give a quick overview of D3JS JavaScript library in this article.
D3JS is a Data Visualization JavaScript library that is used to draw charts, graphs to visualize the data. But here we will use D3JS library animate our traffic lights.
So basically in this project, we will use HTML SVG to draw the UI for traffic signal and after that, we will animate our traffic lights using D3JS. When we will click on the light then the light will on.
Look at a demo below.
Code for the above project:
Create a index.html file and paste the code given below:
<!DOCTYPE html>
<html>
<head>
<title>Traffic Light</title>
<script src="https://d3js.org/d3.v4.js"></script>
<svg id="svg" style="width: 100%; height: 800px;"></svg>
</head>
<body>
<script type="text/javascript">
const svg = d3.select('#svg');
svg.append('rect')
.attr('x', 100)
.attr('y', 10)
.attr('width', 200)
.attr('height', 500)
.style('fill', 'black');
const red = svg.append('circle')
.attr('cx', 200)
.attr('cy', 100)
.attr('r', 75)
.style('fill', 'gray');
const green = svg.append('circle')
.attr('cx', 200)
.attr('cy', 260)
.attr('r', 75)
.style('fill', 'gray');
const yellow = svg.append('circle')
.attr('cx', 200)
.attr('cy', 420)
.attr('r', 75)
.style('fill', 'gray');
red.on('click', function() {
red.style('fill', 'red');
green.style('fill', 'gray');
yellow.style('fill', 'gray');
});
green.on('click', function() {
red.style('fill', 'gray');
green.style('fill', 'green');
yellow.style('fill', 'gray');
});
yellow.on('click', function() {
red.style('fill', 'gray');
green.style('fill', 'gray');
yellow.style('fill', 'yellow');
});
</script>
</body>
</html>