Canvas Rendering
Learn about canvas rendering
Canvas Rendering
What is canvas rendering?
Canvas rendering uses the HTML5 Canvas API to draw graphics, sprites, and animations directly on the screen.
Benefits of canvas rendering?
- Draw custom graphics
- Create game visuals
- Render animations
- Display complex graphics
- Build interactive visuals
// Get canvas and context
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// Draw background
ctx.fillStyle = '#1a1a2e';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw player (rectangle)
ctx.fillStyle = '#00ff00';
ctx.fillRect(100, 300, 50, 50);
// Draw enemy (rectangle)
ctx.fillStyle = '#ff0000';
ctx.fillRect(200, 300, 50, 50);
// Draw circle
ctx.fillStyle = '#ffff00';
ctx.beginPath();
ctx.arc(150, 150, 30, 0, Math.PI * 2);
ctx.fill();
What does this code do?
- Gets canvas element and 2D drawing context
- Draws background rectangle
- Draws player as green rectangle
- Draws enemy as red rectangle
- Draws yellow circle
- Shows basic canvas drawing operations
// Draw a complete game scene
function drawGameScene(ctx, canvas) {
// Draw background
const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
gradient.addColorStop(0, '#1a1a2e');
gradient.addColorStop(1, '#16213e');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw game objects
const gameObjects = [
{ x: 100, y: 300, size: 50, color: '#00ff00' },
{ x: 200, y: 300, size: 50, color: '#ff0000' }
];
gameObjects.forEach(obj => {
ctx.fillStyle = obj.color;
ctx.fillRect(obj.x, obj.y, obj.size, obj.size);
});
// Draw text
ctx.fillStyle = '#ffffff';
ctx.font = '20px Arial';
ctx.fillText('Game Running', 10, 30);
}
What does this code do?
- Creates gradient background for canvas
- Draws multiple game objects using loop
- Sets fill styles for colors
- Renders rectangles and text
- Shows complete game scene rendering
- Demonstrates multiple canvas drawing techniques together
layout: post title: Canvas Rendering description: Learn about canvas rendering permalink: /canvas_rendering author: Vihaan Budhraja —
Try It Yourself
%%js // CODE_RUNNER: canvas-rendering const canvas = document.createElement(‘canvas’); const ctx = canvas.getContext(‘2d’); canvas.width = 200; canvas.height = 200;
ctx.fillStyle = ‘#FF6B6B’; ctx.fillRect(50, 50, 100, 100);
ctx.fillStyle = ‘#4ECDC4’; ctx.fillRect(75, 75, 50, 50);
document.body.appendChild(canvas);