âš ī¸ Warning âš ī¸ Deprecated Code! This video tutorial contains outdated code.
💡 If you wish to update it, any AI assistant will update the code for you in seconds.

2D Context Object and Rectangle Methods

Published : November 17, 2014   •   Last Edited : November 24, 2025   •   Author : Adam Khoury
Welcome to the first exercise of the Canvas Bootcamp. If you are new to canvas element programming, this initial exercise is where you can begin your training. We use JavaScript to deliver all control and assets to our canvas. In this first exercise we will cover the three immediate rectangle methods and discuss the 2D context object and referring back to its corresponding canvas element.
<!DOCTYPE html>
<html>
<head>
<style>
body{ margin:40px; background:#666; }
#my_canvas{ background:#FFF; border:#000 1px solid; }
</style>
<script>
function draw() {
    var ctx = document.getElementById("my_canvas").getContext("2d");
    // You can back-reference the canvas element through the context object
    alert(ctx.canvas.id+" | "+ctx.canvas.width+" | "+ctx.canvas.height);
    ctx.fillRect(20,20,100,100);
    ctx.fillRect(200,200,50,50);
    ctx.strokeRect(20,20,100,100);
    ctx.clearRect(0, 0, 100, 100);
}
window.onload = draw;
</script>
</head>
<body>
<canvas id="my_canvas" width="400" height="300"></canvas>
</body>  
</html>