In addition to translations and rotations, the HTML5 canvas API also provides us with a means for scaling the canvas context. In this recipe, we'll scale down the height of the canvas context using the scale()
method.
Follow these steps to draw a scaled rectangle:
Define the canvas context and the dimensions for the rectangle:
window.onload = function(){ var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); var rectWidth = 150; var rectHeight = 75;
Translate the canvas context and then scale the canvas context height by 50%:
// translate context to center of canvas context.translate(canvas.width / 2, canvas.height / 2); // scale down canvas height by half context.scale(1, 0.5);
Draw a rectangle whose center lies on the top-left corner of the canvas context:
context.fillStyle = "blue"; context.fillRect(-rectWidth / 2, -rectHeight / 2, rectWidth, rectHeight); };
Embed the...