Chapter 62: Plot Canvas
First — What does “Plot Canvas” actually mean?
When students (especially BCA/B.Tech/MCA, data science beginners, web development learners in India) search or ask for “Plot Canvas”, they almost always mean one of two things:
- Using the HTML <canvas> element + JavaScript to draw graphs, charts, plots, curves, data visualizations from scratch (most common meaning when said together with “plot”)
- A confusion / mix-up with Python plotting libraries (Matplotlib, Plotly, Seaborn) that people sometimes call “plot canvas” because Matplotlib has a “canvas” backend concept
But in your context (after we talked about SVG and then Canvas tutorials), you almost certainly mean the first one:
How to create plots / graphs / charts using pure HTML5 Canvas + JavaScript (without external libraries like Chart.js — just raw Canvas code)
This is a very common college lab assignment, mini-project, interview question, or portfolio task: “Draw a line graph / bar chart / sine wave / stock plot using only Canvas”
So today I’m giving you the complete teacher-style Plot Canvas lesson — from zero to good understanding.
2. Why Plot on Canvas? (Real reasons you should care)
- You learn core Canvas skills deeply (paths, lines, text, coordinates, loops, animation)
- No library dependency — pure JavaScript + HTML (good for understanding, interviews)
- Very lightweight — no need to load Chart.js / D3.js
- Full control — you can customize anything (tooltips, zoom, drag, colors…)
- Looks impressive in projects / viva — “I built this chart from scratch”
3. Step-by-Step: How to Plot a Simple Line Graph on Canvas
We’ll build a temperature vs time line plot — exactly like you see in weather apps or science experiments.
Step 1 — Basic Canvas Setup
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Canvas Plot – Temperature Graph</title> <style> canvas { border: 4px solid #2c3e50; background: #ffffff; display: block; margin: 30px auto; box-shadow: 0 4px 15px rgba(0,0,0,0.2); } h1 { text-align: center; color: #34495e; } </style> </head> <body> <h1>Canvas Plot – Temperature vs Time</h1> <canvas id="plotCanvas" width="800" height="500"></canvas> <script> const canvas = document.getElementById('plotCanvas'); const ctx = canvas.getContext('2d'); // Margins (leave space for axes & labels) const margin = { top: 60, right: 40, bottom: 60, left: 60 }; const width = canvas.width - margin.left - margin.right; const height = canvas.height - margin.top - margin.bottom; // Our data: hours 0–24 and temperature °C const data = [ { hour: 0, temp: 22 }, { hour: 3, temp: 20 }, { hour: 6, temp: 19 }, { hour: 9, temp: 24 }, { hour: 12, temp: 30 }, { hour: 15, temp: 32 }, { hour: 18, temp: 29 }, { hour: 21, temp: 26 }, { hour: 24, temp: 23 } ]; // Find min/max for scaling const minTemp = Math.min(...data.map(d => d.temp)) - 2; const maxTemp = Math.max(...data.map(d => d.temp)) + 2; const minHour = 0; const maxHour = 24; // Scale functions (map data values to canvas pixels) function xScale(hour) { return margin.left + (hour - minHour) * (width / (maxHour - minHour)); } function yScale(temp) { return margin.top + (maxTemp - temp) * (height / (maxTemp - minTemp)); } // === Draw axes === ctx.strokeStyle = '#34495e'; ctx.lineWidth = 2; // X axis (hours) ctx.beginPath(); ctx.moveTo(margin.left, margin.top + height); ctx.lineTo(margin.left + width, margin.top + height); ctx.stroke(); // Y axis (temperature) ctx.beginPath(); ctx.moveTo(margin.left, margin.top); ctx.lineTo(margin.left, margin.top + height); ctx.stroke(); // X axis labels ctx.font = '14px Arial'; ctx.fillStyle = '#2c3e50'; ctx.textAlign = 'center'; ctx.textBaseline = 'top'; for (let h = minHour; h <= maxHour; h += 3) { const x = xScale(h); ctx.fillText(h.toString(), x, margin.top + height + 10); } // Y axis labels ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; for (let t = Math.ceil(minTemp); t <= maxTemp; t += 2) { const y = yScale(t); ctx.fillText(t.toString() + '°C', margin.left - 10, y); } // === Draw the actual plot line === ctx.beginPath(); ctx.moveTo(xScale(data[0].hour), yScale(data[0].temp)); for (let i = 1; i < data.length; i++) { ctx.lineTo(xScale(data[i].hour), yScale(data[i].temp)); } ctx.strokeStyle = '#e74c3c'; ctx.lineWidth = 4; ctx.stroke(); // === Add dots at each data point === ctx.fillStyle = '#c0392b'; for (let point of data) { ctx.beginPath(); ctx.arc(xScale(point.hour), yScale(point.temp), 6, 0, Math.PI * 2); ctx.fill(); } // Title ctx.font = 'bold 24px Arial'; ctx.fillStyle = '#34495e'; ctx.textAlign = 'center'; ctx.fillText('Temperature Over 24 Hours', canvas.width / 2, 30); </script> </body> </html> |
What you see when you run it:
- Clean white canvas with axes
- Red line connecting temperature points
- Circles at each data point
- Proper labels on axes (hours 0–24, °C values)
- Title on top
This is a real, good-looking line plot made only with Canvas — no libraries!
4. Step-by-Step: How We Built This Plot (Blackboard Style)
- Canvas setup Fixed size + centered + nice border
- Margins Leave space for axes & labels (very important for readable graphs)
- Data Array of objects {hour, temp} — real data structure
- Scale functions Convert data values → canvas pixels (very common pattern in all plotting code)
- Draw axes & labels Lines + text (textAlign, textBaseline)
- Plot the linebeginPath() → moveTo first point → lineTo all others → stroke()
- Add data points Small circles for visual clarity
- Title Centered at top
5. Teacher’s Quick Tips (Hyderabad Student Style 😄)
- Always leave margins — otherwise labels get cut off
- Use clearRect() if you want to animate / update the plot
- Common mistake #1: Wrong scale function → graph upside down or squashed
- Common mistake #2: No beginPath() before line → connects to previous drawing
- Common mistake #3: Hardcode coordinates — always use scale functions
- Pro tip: Add ctx.lineCap = ’round’ for smooth line ends
- Pro tip 2: For real projects add tooltips (on mouse hover show exact value)
Understood how to plot on Canvas now? This is a very strong intermediate project — you learned coordinates, paths, text, scaling, real data mapping.
Tell me honestly — what do you want next?
- Add interactive tooltip on hover?
- Multiple lines (temperature + humidity)?
- Bar chart version of same data?
- Animated line drawing (line grows over time)?
- Or 15-question Canvas plotting quiz?
Just say — we can make any graph or chart together! 🚀
