HTML5 Canvas Tutorial: transformations – scaling

Canvas Transformations: scaling

To bring an enlargement/reduction of sizes of an object to effect on an HTML5 Canvas we can use the scale() method. The scale transformation is described by means of the scaleX and scaleY parameters.

context.scale(scaleX,scaleY);

Example 1: Canvas transformations: scaling in the x direction. See image 1.

<!doctype html>
<html>
<head>
<title>Canvas Transformaties: schalen in  x richting van vierkant </title>
<script> 
function scaling(){
    var canvas = document.getElementById("transformations");
    var context = canvas.getContext("2d");
 
    var rectangularWidth = 150;
    var rectangularHeight =150;
 
    // translate context to the center of the Canvas
    context.translate(canvas.width / 2, canvas.height / 2);
 
    // decrease the x component with 0.25 (4 times smaller)
    context.scale(0.25,1);
 
    context.fillStyle = "#f16529";
    context.fillRect(-rectangularWidth / 2, -rectangularHeight / 2, rectangularWidth, rectangularHeight);
};
    window.addEventListener("load", scaling, true);
</script>
</head>
<body>	
	<canvas id="transformations" style="border: 1px solid;" width="400" height="210"></canvas>
</body>
</html>
Canvas Transformaties: de translatie.
Image 1. Canvas transformations: scaling in the x direction. See image 1.

Check this example in your browser

Next tutorial

Leave a comment