Back to Explore
GuideVibeFix editorialUpdated Nov 20, 2026

Drawing without images: Canvas basics, explained plainly

No image files, no library: the order page's weekly bar chart and smiley face are drawn live with Canvas. This guide follows MDN's Canvas tutorial — Basic usage, Drawing shapes, and Applying styles and colors: the 300×150 default, the top-left origin, fillRect and strokeRect, the beginPath-moveTo-lineTo-fill/stroke path pattern, arcs in radians, Bezier curves, fillStyle and strokeStyle, transparency, line styles, gradients, patterns, shadows, and redrawing for motion.

Real photo: a hand holding a stylus draws a colorful picture on a tablet, with a paint palette and brushes on the desk

First, the boundaries. The site already has several JavaScript basics guides: array methods, destructuring, Map and Set, Promise and async/await, try/catch, DOM querying and traversal, and module import/export. This guide covers none of them. It covers one thing: the patch of the page you can draw on with code — the Canvas. The “Greenstone Cafe” below is the same fictional practice project as before: a small web tool that takes orders for a street-corner cafe. Earlier guides covered how its order page works and how its code is split into modules. This one is about a small canvas on that page: a “weekly orders” bar chart at the top of the order page, and a smiley face on the “today's pick” card, both drawn live with Canvas rather than pulled from an image library. Every operation, code sample, and number built around it is invented to explain the technique, not a real record. Everything about Canvas syntax and behavior comes from three MDN pages — “Basic usage of canvas”, “Drawing shapes with canvas”, and “Applying styles and colors” from the Canvas tutorial. The sources are listed in this article's meta information and evidence record. The examples in the docs — two intersecting rectangles, a smiley face, twelve arcs, a speech balloon and a heart, a 6×6 color palette — are the docs' own examples, not real services. This guide does not cover drawing text, drawing images, transformations, compositing and clipping, pixel manipulation, or WebGL — only the most-used 2D set: setting up, drawing shapes, coloring, stroking lines, gradients, and motion. By the end you should be able to do four things: set up a canvas, draw rectangles and paths, color and stroke shapes, and know where to look when a drawing comes out wrong.

Step 1: Canvas has only two attributes, so set up the frame first

The first lesson is that canvas is first of all an HTML element. It looks a bit like an img, but it has no src and no alt. MDN's “Basic usage of canvas” says it plainly: the canvas element has only two attributes, width and height. Both are optional and can also be set through DOM properties. When no width and height are specified, the canvas starts out 300 pixels wide and 150 pixels high. Setting up looks like one line: <canvas id="canvas" width="150" height="150"></canvas>. Three rules are easy to trip over here. First, CSS can change how big the canvas appears on the page, but that only stretches or squeezes the finished drawing to fit the display size; if the CSS ratio does not match the canvas's own width-to-height ratio, the drawing comes out distorted. MDN's advice is direct: if your rendering looks distorted, write the width and height attributes on the canvas tag itself and do not size the canvas with CSS. Second, the canvas element requires its closing tag </canvas>. That is because fallback content lives inside the tag; without the closing tag, the browser treats the rest of the document as fallback content and nothing on the page displays. Third, with no styling rules applied, the canvas starts out fully transparent, so do not assume your code failed to run when you see nothing. The cafe's bar chart is set up exactly this way: <canvas id="weekChart" width="300" height="150">Weekly orders bar chart</canvas>, width and height written on the tag, no CSS sizing, and a line of fallback text inside. Once the frame is up, JavaScript does the drawing: first grab the canvas, then ask it for a 2D rendering context: const canvas = document.getElementById("weekChart"); const ctx = canvas.getContext("2d");. The first line finds the canvas node with getElementById; the second calls its getContext("2d") method and gets back a CanvasRenderingContext2D object, and every drawing method and property after that hangs off this ctx. MDN also shows a safer version: test that canvas.getContext exists first, draw only if it does, and fall back otherwise, so old browsers do not throw. The rule to remember: the canvas is the board, ctx is the brush; the canvas only carries width and height, and ctx decides what gets drawn.

Step 2: The origin sits in the top-left corner, so forget the math-class habit

Before putting pen to canvas, learn the coordinate system. MDN's “Drawing shapes with canvas” opens with it: the canvas grid, or coordinate space, has its origin in the top-left corner, at coordinate (0,0); x grows to the right and y grows downward. Normally one unit in the grid is one pixel on the canvas. That is the opposite of the math-class habit, where larger y means higher up; on a canvas, larger y means lower down. Beginners trip here most often: you want a balloon to float upward, write a small y, and the balloon sinks; you want a bar to grow upward from the bottom and the bar grows downward from the top instead. The cafe bar chart is a good example: the canvas is 150 pixels tall, and for a bar to grow upward from the bottom, the top of the bar has to be computed as the bottom edge, 150, minus the bar's height. MDN adds that later you can translate the origin elsewhere, rotate the grid, and scale it, but for now the default is enough. One more contrast to remember: unlike SVG, which has circles, polygons, and every shape under the sun, canvas only supports two primitive shapes, rectangles and paths; everything else has to be built by combining paths. Rectangles come with ready-made methods; paths have to be drawn stroke by stroke. The rule to remember: the origin is top-left and larger y means lower down; canvas has only rectangles and paths as primitive shapes.

Step 3: The three rectangle methods, drawn the moment you call them

With the grid understood, start with the simplest shape: the rectangle. MDN's “Drawing shapes” lists three rectangle methods, all taking the same parameters: fillRect(x, y, width, height) draws a filled rectangle; strokeRect(x, y, width, height) draws only the rectangular outline; clearRect(x, y, width, height) clears the given rectangular area, making it fully transparent. x and y are the position of the rectangle's top-left corner, width and height its size. MDN's example runs all three in a row: ctx.fillRect(25, 25, 100, 100) draws a large black square 100 pixels on each side; ctx.clearRect(45, 45, 60, 60) erases a 60×60 square from the center; ctx.strokeRect(50, 50, 50, 50) draws a 50×50 outline inside the cleared square. Three lines, three methods, and all of them draw immediately — unlike path methods, which first collect and then render. The cafe bar chart is drawn with fillRect, one bar per day: seven bars, x stepping left to right, y computed as “canvas bottom minus bar height”, width fixed at 30, height from that day's order count. One thing to watch: MDN points out that strokeRect(50, 50, 50, 50) looks 50×50 but really occupies 52×52, and its edges come out gray and two pixels wide. That is the old stroke problem, and step 9 explains how to fix it. The rule to remember: fillRect fills solid, strokeRect draws the outline, clearRect erases; rectangles need no path, the call itself draws.

Step 4: Paths in three steps — collect first, draw second

Everything beyond rectangles goes through paths. MDN's “Drawing shapes” breaks path drawing into three steps: first, call beginPath() to start a new path; second, use path-drawing methods to add lines to the path; third, call fill() to fill the area the path encloses, or stroke() to draw along the path. A path is a list of points joined by segments — straight or curved, of different widths and colors — and one path can hold several unconnected sub-paths. beginPath() is the thing to do before every new shape: it resets the list of sub-paths so you can start building a fresh shape. Forgetting beginPath() is the most common beginner mistake: the previous shape's path is still in the list, so when the new shape is stroked, the old shape's outline gets stroked again and extra lines appear out of nowhere. The three most-used path methods are moveTo(x, y), which lifts the “pen” to the given coordinates without drawing — MDN compares it to lifting a pencil off paper and placing it at the next spot; lineTo(x, y), which draws a straight line from the current position to the given coordinates; and closePath(), which draws a straight line from the current point back to the start of the current sub-path, closing the shape. MDN's triangle example is the model for all three steps: ctx.beginPath(); ctx.moveTo(25, 25); ctx.lineTo(105, 25); ctx.lineTo(25, 105); ctx.fill(); — three sides enclosed, filled, one solid triangle. The stroked version needs one more step: fill() closes open shapes automatically, but stroke() does not, so without closePath() a stroked triangle comes out with only two sides and a missing edge. MDN's smiley face pushes the pattern further: one big arc for the outer circle, a half arc for the mouth, two small arcs for the eyes, moveTo() lifting the pen between each, and a single stroke() at the end. The smiley on the cafe's “today's pick” card follows that example: outer circle, mouth, eyes, four arcs, three moveTo() calls, one stroke(). The rule to remember: beginPath() opens a new path, moveTo() lifts the pen, lineTo() draws the line, fill() fills and closes automatically, stroke() strokes without closing.

Step 5: Arcs and angles — radians are not degrees

Once straight lines work, the next step is circles and arcs. MDN's “Drawing shapes” gives two methods: arc(x, y, radius, startAngle, endAngle, counterclockwise) and arcTo(x1, y1, x2, y2, radius). arc takes six parameters, each worth knowing: x and y are the coordinates of the circle's center, radius is the radius, startAngle and endAngle are where the arc starts and ends, measured in radians from the x axis, and counterclockwise is a Boolean — true draws counterclockwise, and the default is clockwise. Radians are where people slip most: arc wants radians, not degrees. For a full circle, start at 0 and end at Math.PI * 2; for a half circle, end at Math.PI. MDN gives the conversion: radians = (Math.PI / 180) * degrees — multiply the degrees by Math.PI and divide by 180. The cafe smiley's eyes are drawn that way: ctx.arc(60, 65, 5, 0, Math.PI * 2, true), center (60, 65), radius 5, from 0 to Math.PI * 2, counterclockwise, one full circle. MDN's twelve-arcs example is worth practicing once: two nested for loops, 4 rows and 3 columns, center x at 25 + j * 50 and y at 25 + i * 50, radius fixed at 20, start angle fixed at 0, end angle starting at Math.PI and growing by Math.PI / 2 each column, a full circle in the last column; clockwise or counterclockwise depends on whether the row number i is odd or even, and the top two rows are stroked while the bottom two are filled. One picture, twelve arcs, clockwise and counterclockwise plus stroke and fill all practiced at once. arcTo is the other way to draw an arc: give two control points and a radius, and it draws an arc tangent to the previous line — the usual tool for rounded corners. MDN's roundedRect utility is four arcTo calls in a row, one per corner, finished with a single stroke(). The rule to remember: arc wants radians, and a full circle is Math.PI * 2; convert degrees before passing them in.

Step 6: Bezier curves — the control points are in charge

Straight lines and arcs handle neat shapes; for something organic with a bend in it, bring in Bezier curves. MDN's “Drawing shapes” gives two methods: quadraticCurveTo(cp1x, cp1y, x, y) draws a quadratic Bezier curve, and bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) draws a cubic Bezier curve. In both methods, x and y are the curve's end point; the difference is the number of control points: a quadratic curve has one, a cubic curve has two. A control point does not sit on the curve — it pulls the curve toward itself: the farther the control point, the harder the bend, and two control points can pull out an S shape. MDN puts it honestly: unlike vector software such as Adobe Illustrator, there is no direct visual feedback while drawing Bezier curves on canvas, so complex shapes take patience. Its two examples are one of each kind: the quadratic example draws a speech balloon with six quadraticCurveTo segments, the little tail pulled out by control points; the cubic example draws a heart with eight bezierCurveTo segments, symmetrical top to bottom, four segments per side. The little heart on the cafe's “today's pick” card follows MDN's heart example: ctx.moveTo(75, 40) to place the pen, then eight bezierCurveTo segments and one fill(). A practical trick for Bezier curves: mark the start point, end point, and control points on paper first, then write the code — it saves a lot of guessing. The rule to remember: quadratic curves take one control point, cubic curves take two; the control points pull the curve but never lie on it.

Step 7: Color is last-write-wins, so put it back when you are done

With shapes working, the next step is color. MDN's “Applying styles and colors” opens with two properties: fillStyle sets the style used when filling shapes, and strokeStyle sets the style for shapes' outlines. Either value can be a CSS color string, a gradient object, or a pattern object; both default to black, CSS color value #000000. MDN's example makes the point clearly: ctx.fillStyle = "orange", ctx.fillStyle = "#FFA500", ctx.fillStyle = "rgb(255 165 0)", and ctx.fillStyle = "rgb(255 165 0 / 100%)" all describe the same orange. Any CSS color spelling works — color names, hex, rgb(). The rule MDN stresses most is this: once you set strokeStyle or fillStyle, the new value becomes the default for all shapes drawn from then on; for every shape you want in a different color, you must reassign the property. Forgetting to put it back is the most common coloring accident: you paint one orange bar, forget to reset fillStyle, and every bar after it comes out orange. The cafe bar chart follows the rule: inside the loop, each day's color is assigned before drawing, ctx.fillStyle = "#FE4A16"; ctx.fillRect(x, y, 30, h);, color and shape matched one to one. MDN's 6×6 palette example practices the same idea to the limit: two nested for loops, 36 little squares, the red and green channels computed from the row and column, the blue channel fixed at 0, and the result reads like a gradient palette from black through yellow to red. The stroked-circles version does the same with strokeStyle and arc(). The rule to remember: fillStyle colors the fill, strokeStyle colors the outline; a changed color stays the default, so reassign before the next shape that needs a different one.

Step 8: Transparency has two spellings, and they are not the same

Besides solid color, canvas can draw semi-transparent shapes. MDN's “Applying styles and colors” gives two ways: the globalAlpha property, or a semi-transparent color assigned to the stroke or fill style. globalAlpha takes a value from 0.0 (fully transparent) to 1.0 (fully opaque) and defaults to 1.0; once set, it applies to all shapes drawn afterward. MDN's own guidance is that globalAlpha is handy when many shapes share similar transparency, but otherwise it is generally more useful to set transparency on individual shapes through their colors. A transparent color is written with a slash in rgb(): ctx.fillStyle = "rgb(255 0 0 / 50%)" is half-transparent red; the transparency can be a percentage from 0% to 100% or a number from 0.0 to 1.0. The difference matters: globalAlpha is a blanket rule — everything drawn after it follows it, including shapes whose color you change later; a color's own transparency is per-shape and touches only that one shape. MDN's two examples draw the contrast clearly: the first draws four colored background squares, sets globalAlpha to 0.2, then loops seven white circles of growing radius on top; the circles pile up layer by layer, growing less transparent toward the middle, until the result looks like a radial gradient. The second uses the same background but gives each white bar its own opacity, (i + 1) / 10, from 10% up to 100%, so every bar differs. The cafe bar chart uses the second way: the best-selling day's bar is solid, and the other bars use the same color at 60% opacity, so the best day stands out at a glance. The rule to remember: globalAlpha covers every shape after it, a color's own transparency covers only that shape; for fine control, use the latter.

Step 9: Line width, line ends, and corners — blur usually starts here

After color comes line styling. MDN's “Applying styles and colors” lists six line properties and methods: lineWidth sets the width of lines, default 1.0, and values must be positive numbers; lineCap sets how line ends look — butt, round, and square, default butt; lineJoin sets how corners where lines meet look — round, bevel, and miter, default miter; miterLimit caps how far a miter can extend, default 10.0; getLineDash() returns the current dash pattern; setLineDash(segments) sets it; and lineDashOffset sets where the dash pattern starts. One fact about lineWidth explains a lot: the line's thickness is centered on the path, extending half the line width to either side. That is why the stroked rectangle in step 3 came out gray and two pixels wide: the coordinates fell on whole-number grid lines, so a 1-unit line covered half of the pixel on each side, and both pixels were only half shaded. MDN's fix is to draw a 1-unit vertical line at a half-pixel coordinate such as 3.5, so the line fills exactly one pixel; for even-width lines, put the path between pixels instead. The three lineCap values are easy to picture: butt squares the ends off flush at the endpoints; round adds a semicircle with a radius half the line width; square adds a box with an equal width and half the line width. MDN's example draws three vertical lines at lineWidth 15 with the three caps, plus two blue guide lines, so the difference is visible at once. The three lineJoin values are: round fills the corner with a rounded sector; bevel fills a triangular area, cutting the corner flat; miter extends the outside edges until they meet at a single point, making the sharpest corner. miterLimit defaults to 10.0, meaning a corner that would stretch too far falls back to a bevel — MDN works out that the default limit strips miters for sharp angles below about 11 degrees. setLineDash draws dashed lines: pass an array of numbers that alternate draw length and gap length, such as [4, 2] for draw 4, gap 2; lineDashOffset shifts where the pattern begins. The rule to remember: line width spreads half to each side of the path; a 1-pixel line needs a half-pixel coordinate to stay crisp; a dashed line is draw-gap-draw-gap.

Step 10: Gradients, patterns, and shadows — color can have a shape too

Beyond solid colors, fillStyle and strokeStyle also accept gradients and patterns. MDN's “Applying styles and colors” gives three gradient builders: createLinearGradient(x1, y1, x2, y2) makes a linear gradient from a start point to an end point; createRadialGradient(x1, y1, r1, x2, y2, r2) makes a radial gradient between two circles; createConicGradient(angle, x, y) makes a conic gradient circling a point, with the angle in radians. Once a CanvasGradient object exists, addColorStop(position, color) adds color stops: position is a number from 0.0 to 1.0 for the color's relative place in the gradient, and color is a CSS color string. MDN's linear example is typical: const linGrad = ctx.createLinearGradient(0, 0, 0, 150); linGrad.addColorStop(0, "#00ABEB"); linGrad.addColorStop(0.5, "white"); linGrad.addColorStop(0.5, "#26C000"); linGrad.addColorStop(1, "white"); — note that position 0.5 carries two colors, white and green, so the transition cuts hard at 0.5 and makes a sharp dividing line; for a soft blend, do not crowd stops onto one position. The radial example layers four gradients with slightly offset centers for a spherical 3D effect, and the conic example has one gradient fading green to white and one alternating black and white every quarter turn for a checkerboard. Patterns use createPattern(image, type), where image can be an image, another canvas, or a video, and type is repeat, repeat-x, repeat-y, or no-repeat — the same meanings as CSS background-repeat: tile both ways, tile horizontally only, tile vertically only, or use once. Patterns have one hard rule: the image must be loaded before the method is called, or the pattern may be drawn incorrectly; MDN's example builds the pattern inside img.onload. Shadows take four properties: shadowOffsetX and shadowOffsetY say how far the shadow extends horizontally and vertically, both default 0; shadowBlur is the size of the blurring effect, default 0; shadowColor is a standard CSS color, default fully-transparent black. MDN's example gives a text string a shadow with shadowOffsetX = 2, shadowOffsetY = 2, shadowBlur = 2, and shadowColor = "rgb(0 0 0 / 50%)", and the text lifts off the page. The cafe bar chart uses a linear gradient: each bar fades from bright orange #FE4A16 at the top to a deeper orange at the bottom, with a solid edge on top. The rule to remember: build the gradient object first, then add color stops from 0 to 1; use a pattern only after its image has loaded; shadows need offset, blur, and color.

Step 11: Counting the mistakes — six ways to go wrong cover everything

Ten steps covered the techniques; this step counts the most common mistakes. The Greenstone Cafe order page is a fictional practice project, and the numbers below are invented examples matched against the pitfalls in the ten steps above — they are not statistics from any real project. In one month of canvas work on the order page, drawings went wrong 144 times, in six ways. Forgetting beginPath, so a new shape stroked the old path along with it: 36 times, 25.0%. Mixing up the origin, or forgetting clearRect before redrawing: 30 times, 20.8%. Changing fillStyle and forgetting to change it back, so later shapes inherited the wrong color: 26 times, 18.1%. Passing degrees to arc as if they were radians, so every arc came out wrong: 22 times, 15.3%. Stroking without a half-pixel coordinate, so lines came out blurry and gray: 18 times, 12.5%. Stretching the canvas with CSS, so the picture looked squashed: 12 times, 8.3%. 36 + 30 + 26 + 22 + 18 + 12 = 144, and 25.0 + 20.8 + 18.1 + 15.3 + 12.5 + 8.3 = 100.0%, so the books balance. The top three are rules not remembered; the last three are numbers not worked out.

Bar chart of the causes behind 144 Canvas drawing mistakes in one month

When you read this chart, do not just look at the longest bar — look at which earlier step each bar belongs to. Forgetting beginPath is the step 4 pitfall, mixing up the origin is step 2, fillStyle not put back is step 7, radians are step 5, blurry strokes are step 9, and CSS stretching is step 1. A mistake is not scary; not knowing which step it came from is. Trace the bar back to its step and the fix gets fast.

Step 12: Motion means redrawing, so run the checklist before you ship

The last lesson is motion. Canvas differs from the DOM in one big way: once drawn, it is forgotten. Change an attribute on a DOM element and the page updates; a shape drawn on canvas has no node behind it, so it cannot be changed — only erased and redrawn. MDN's “Applying styles and colors” marching-ants example is the model for this: first clearRect(0, 0, canvas.width, canvas.height) wipes the whole canvas clean, then setLineDash([4, 2]) sets the dash pattern, lineDashOffset = -offset shifts the dash start by one, and strokeRect(10, 10, 100, 100) redraws the box; then the march() function adds one to offset, resets it to 0 past 5, redraws, and calls setTimeout(march, 20) to run again in 20 milliseconds. The box itself never moves — only the dash start moves, one step at a time, and it looks like ants marching around the border. The cafe bar chart animation follows the same idea: the data stays the same and only the bar heights grow from 0 to their targets; every frame clears with clearRect first, then redraws all seven bars at their current heights. Before shipping canvas code, run this checklist: one, did the canvas tag get width and height, a closing tag, and fallback content inside; two, did you check the browser supports getContext("2d") before calling it; three, did every new shape start with beginPath(); four, did arc get radians, with degrees converted; five, did fillStyle and strokeStyle get put back before the next shape that needs a different color; six, did 1-pixel strokes land on half-pixel coordinates; seven, did a pattern's image finish loading in onload; eight, does every animation frame start with clearRect. Pass all eight, then look at the result. Plenty is left unexpanded here: drawing text with font and fillText, drawing images with drawImage, translating, rotating, and scaling, compositing and clipping, pixel manipulation, real animation with requestAnimationFrame, and fixing blurry canvas on high-density screens — MDN's tutorial has a chapter for each, and the next guide will take them up one by one.

Views 0Comments 0

Comments (0)

ME
0/1000
Loading comments...

Sources

Browse projectsPublish your project

Related articles

Real photo: hands typing on a MacBook Pro showing JavaScript code that changes HTML content, with a white mouse, papers, and binders on a white desk
Guide
Functions without the confusion: JavaScript functions, parameters, and arrow functions, explained plainly

You already call functions every day; this guide names what you have been doing. Following MDN's Functions, Arrow function expressions, and Rest parameters: declarations versus expressions, parameters and arguments, default values, rest parameters, spread syntax, return values, arrow function shorthand, the this trap, callbacks, and scope.

Tool TipsFrontend EngineeringAI Coding
Real photo: a Casio scientific calculator on a wooden desk showing 123456789 + 987654321 = 1111111110, beside handwritten math notebooks, a pen, a mug, and a laptop edge
Guide
Don't let 0.1 + 0.2 break your bill: JavaScript numbers and Math, explained plainly

Numbers in JavaScript are one type, Number, stored as 64-bit floats — which is why 0.1 + 0.2 is 0.30000000000000004. This guide follows MDN's Basic math in JavaScript, Math, and Number: one number type, float error, counting money in cents, converting strings, NaN and Infinity, safe integers, the four rounding methods, Math.random, the Math toolbox, and formatting for display.

Tool TipsFrontend EngineeringAI Coding
Real photo: over-the-shoulder view of a man typing CSS code on a laptop, selectors visible on screen, with coffee, glasses, and a phone on the desk
Guide
Getting styles onto the right elements: CSS selectors, explained plainly

A selector is the first part of a rule: it decides who the styles land on. This guide follows MDN's Basic CSS selectors, Attribute selectors, and Pseudo-classes and pseudo-elements: type, class, ID, selector lists, universal, attribute selectors, pseudo-classes, pseudo-elements, chaining them together, plus a checklist for when a style does not show up.

Tool TipsFrontend EngineeringAI Coding