Introduction
HTML5 Canvas allows developers to draw and manipulate images directly on the web page. This tutorial will guide you on how to translate, rotate, and scale images using JavaScript. By understanding these concepts, you can create complex visual effects in your HTML5 games and animations.
Code Overview
The following code demonstrates how to load images onto the canvas and apply transformations such as scaling, rotation, and translation:
Live Demo
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<script type="text/javascript">
function pageLoaded() {
var canvas = document.getElementById("testCanvas");
var context = canvas.getContext("2d");
// Load multiple images
var star = document.getElementById("star");
var heart = document.getElementById("heart");
var diamond = document.getElementById("diamond");
// Original image
context.drawImage(star, 10, 10);
// Scaled image
context.drawImage(star, 150, 10, 50, 50);
// Rotated heart
context.save();
context.translate(300, 100);
context.rotate(Math.PI / 4);
context.drawImage(heart, -25, -25, 50, 50);
context.restore();
// Multiple rotated diamonds
for(var i = 0; i < 8; i++) {
context.save();
context.translate(450, 200);
context.rotate((Math.PI/4) * i);
context.drawImage(diamond, -25, -25, 50, 50);
context.restore();
}
// Scaled and translated pattern
for(var j = 0; j < 3; j++) {
context.save();
context.translate(100 * j, 300);
context.scale(0.8, 0.8);
context.drawImage(star, 0, 0, 50, 50);
context.restore();
}
}
</script>
</head>
<body onload="pageLoaded();">
<!-- Hidden image elements for canvas -->
<img src="/api/placeholder/50/50" id="star" style="display: none;">
<img src="/api/placeholder/50/50" id="heart" style="display: none;">
<img src="/api/placeholder/50/50" id="diamond" style="display: none;">
<canvas width="640" height="480" id="testCanvas" style="border: 1px solid black;">
Your browser does not support HTML5 canvas. Please shift to a new browser
</canvas>
</body>
</html>
Explanation of the Code
The code starts by retrieving the canvas element and its drawing context. Three images (star, heart, and diamond) are loaded using their respective IDs.
- Original Image: The
context.drawImage()method draws the star image at (10, 10). - Scaled Image: The star image is drawn again but with a reduced size of 50x50 pixels.
- Rotated Heart: The heart image is rotated by 45 degrees using
context.rotate()and then drawn on the canvas. - Multiple Rotated Diamonds: A loop rotates the diamond image eight times around a central point, creating a circular pattern.
- Scaled Pattern: The star image is scaled down to 80% of its original size and drawn in a repeating pattern using translation.
Conclusion
With HTML5 Canvas, you can create rich visual content by applying transformations like translation, scaling, and rotation. This tutorial provides the foundation for building complex graphics, animations, and interactive elements for your web applications.