JavaScript: Draw two intersecting rectangles, one of which has alpha transparency
JavaScript Drawing: Exercise-3 with Solution
Intersecting Rectangles
Write a JavaScript program to draw two intersecting rectangles, one with Alpha transparency.
Sample output :

Sample Solution:
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Draw two intersecting rectangles, one of which has alpha transparency</title>
</head>
<body onload="draw();">
<canvas id="canvas" width="150" height="150"></canvas>
</body>
</html>
JavaScript Code:
function draw()
{
var canvas = document.getElementById("canvas");
if (canvas.getContext)
{
var context = canvas.getContext("2d");
context.fillStyle = "rgb(256,0,0)";
context.fillRect (15, 10, 55, 50);
context.fillStyle = "rgba(0, 0, 200, 0.6)";
context.fillRect (35, 30, 55, 50);
}
}
Live Demo:
See the Pen javascript-drawing-exercise-3 by w3resource (@w3resource) on CodePen.
For more Practice: Solve these Related Problems:
- Write a JavaScript program to draw two overlapping rectangles with different levels of transparency and a distinct border for the intersection area.
- Write a JavaScript program to draw intersecting rectangles where one rectangle is rotated relative to the other.
- Write a JavaScript program to draw two intersecting rectangles filled with different patterns (e.g., stripes and dots) and highlight their overlapping section.
- Write a JavaScript program to draw two intersecting rectangles and animate the transparency of one so that the intersection dynamically changes color.
Go to:
PREV : Draw Circle.
Next: Right-Angled Triangle.
Improve this sample solution and post your code through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.