Menu
×
   ❮     
HTMLCSSJAVASCRIPTSQLPYTHONJAVAPHPHOW TOW3.CSSCC++C#BOOTSTRAPREACTMYSQLJQUERYEXCELXMLDJANGONUMPYPANDASNODEJSDSATYPESCRIPTANGULARGITPOSTGRESQLMONGODBASPAIRGOKOTLINSASSVUEGEN AISCIPYCYBERSECURITYDATA SCIENCEINTRO TO PROGRAMMINGBASH

JS Reference

JS by CategoryJS by Alphabet

JavaScript

JS ArraysJS BooleanJS ClassesJS DatesJS ErrorJS GlobalJS JSONJS MapsJS MathJS NumbersJS ObjectsJS OperatorsJS PrecedenceJS PromisesJS RegExpJS SetsJS StatementsJS StringsJS TypedArray

Window

Window ObjectWindow ConsoleWindow HistoryWindow LocationWindow NavigatorWindow Screen

HTML DOM

HTML DocumentsHTML ElementsHTML AttributesHTML CollectionHTML NodeListHTML DOMTokenListHTML Styles
alignContentalignItemsalignSelfanimationanimationDelayanimationDirectionanimationDurationanimationFillModeanimationIterationCountanimationNameanimationTimingFunctionanimationPlayStatebackgroundbackgroundAttachmentbackgroundClipbackgroundColorbackgroundImagebackgroundOriginbackgroundPositionbackgroundRepeatbackgroundSizebackfaceVisibilityborderborderBottomborderBottomColorborderBottomLeftRadiusborderBottomRightRadiusborderBottomStyleborderBottomWidthborderCollapseborderColorborderImageborderImageOutsetborderImageRepeatborderImageSliceborderImageSourceborderImageWidthborderLeftborderLeftColorborderLeftStyleborderLeftWidthborderRadiusborderRightborderRightColorborderRightStyleborderRightWidthborderSpacingborderStyleborderTopborderTopColorborderTopLeftRadiusborderTopRightRadiusborderTopStyleborderTopWidthborderWidthbottomboxShadowboxSizingcaptionSidecaretColorclearclipcolorcolumnCountcolumnFillcolumnGapcolumnRulecolumnRuleColorcolumnRuleStylecolumnRuleWidthcolumnscolumnSpancolumnWidthcounterIncrementcounterResetcssFloatcursordirectiondisplayemptyCellsfilterflexflexBasisflexDirectionflexFlowflexGrowflexShrinkflexWrapfontfontFamilyfontSizefontStylefontVariantfontWeightfontSizeAdjustheightisolationjustifyContentleftletterSpacinglineHeightlistStylelistStyleImagelistStylePositionlistStyleTypemarginmarginBottommarginLeftmarginRightmarginTopmaxHeightmaxWidthminHeightminWidthobjectFitobjectPositionopacityorderorphansoutlineoutlineColoroutlineOffsetoutlineStyleoutlineWidthoverflowoverflowXoverflowYpaddingpaddingBottompaddingLeftpaddingRightpaddingToppageBreakAfterpageBreakBeforepageBreakInsideperspectiveperspectiveOriginpositionquotesresizerightscrollBehaviortableLayouttabSizetextAligntextAlignLasttextDecorationtextDecorationColortextDecorationLinetextDecorationStyletextIndenttextOverflowtextShadowtextTransformtoptransformtransformOrigintransformStyletransitiontransitionPropertytransitionDurationtransitionTimingFunctiontransitionDelayunicodeBidiuserSelectverticalAlignvisibilitywidthwordBreakwordSpacingwordWrapwidowszIndex

HTML Events

HTML EventsHTML Event ObjectsHTML Event PropertiesHTML Event Methods

Web APIs

API CanvasAPI ConsoleAPI FetchAPI FullscreenAPI GeolocationAPI HistoryAPI MediaQueryListAPI StorageAPI ValidationAPI Web

HTML Objects

<a><abbr><address><area><article><aside><audio><b><base><bdo><blockquote><body><br><button><canvas><caption><cite><code><col><colgroup><datalist><dd><del><details><dfn><dialog><div><dl><dt><em><embed><fieldset><figcaption><figure><footer><form><head><header><h1> - <h6><hr><html><i><iframe><img><ins><input> button<input> checkbox<input> color<input> date<input> datetime<input> datetime-local<input> email<input> file<input> hidden<input> image<input> month<input> number<input> password<input> radio<input> range<input> reset<input> search<input> submit<input> text<input> time<input> url<input> week<kbd><label><legend><li><link><map><mark><menu><menuitem><meta><meter><nav><object><ol><optgroup><option><output><p><param><pre><progress><q><s><samp><script><section><select><small><source><span><strong><style><sub><summary><sup><table><tbody><td><tfoot><th><thead><tr><textarea><time><title><track><u><ul><var><video>

Other References

CSSStyleDeclarationJS Conversion


Canvas API

The HTML <canvas> element is a bitmapped area in an HTML page.

The Canvas API allows JavaScript to draw graphics on the canvas.

The Canvas API can draw shapes, lines, curves, boxes, text, and images, with colors, rotations, transparencies, and other pixel manipulations.

Example

<canvas id="myCanvas" width="300" height="150"></canvas>
Try it Yourself »

You access a <canvas> element with the HTML DOM method getElementById().

To draw in the canvas you need to create a 2D context object:

const myCanvas = document.getElementById("myCanvas");
const ctx = myCanvas.getContext("2d");

Note

The HTML <canvas> element itself has no drawing abilities.

You must use JavaScript to draw any graphics.

The getContext() method returns an object with tools (methods) for drawing.


Paths

The common way to draw on the canvas is to:

  1. Begin a Path - beginPath()
  2. Move to a Point - moveTo()
  3. Draw in the Path - lineTo()
  4. Draw the Path - stroke()

Example

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(20, 100);
ctx.lineTo(70, 100);
ctx.stroke();
Try it Yourself »

Complete Canvas API Reference

This reference covers all Properties and Methods of the getContext("2d") Object, used to draw text, lines, boxes, circles, pictures, and more on the canvas.

Drawing Methods

There are only 3 methods to draw directly on the canvas:

MethodDescription
fillRect()Draws a "filled" rectangle
strokeRect()Draws a rectangle (with no fill)
clearRect()Clears specified pixels within a rectangle

Path Methods

MethodDescription
beginPath()Begins a new path or resets the current path
closePath()Adds a line to the path from the current point to the start
isPointInPath()Returns true if the specified point is in the current path
moveTo()Moves the path to a point in the canvas (without drawing)
lineTo()Adds a line to the the path
fill()Fills the current path
rect()Adds a rectangle to the path
stroke()Draws the current path
 Circles and Curves
bezierCurveTo()Adds a cubic Bézier curve to the path
arc()Adds an arc/curve (circle, or parts of a circle) to the path
arcTo()Adds an arc/curve between two tangents to the path
quadraticCurveTo()Adds a quadratic Bézier curve to the path


Text

Method/PropDescription
directionSets or returns the direction used to draw text
fillText()Draws "filled" text on the canvas
fontSets or returns the font properties for text content
measureText()Returns an object that contains the width of the specified text
strokeText()Draws text on the canvas
textAlignSets or returns the alignment for text content
textBaselineSets or returns the text baseline used when drawing text

Colors, Styles, and Shadows

Method/PropertyDescription
addColorStop()Specifies the colors and stop positions in a gradient object
createLinearGradient()Creates a linear gradient (to use on canvas content)
createPattern()Repeats a specified element in the specified direction
createRadialGradient()Creates a radial/circular gradient (to use on canvas content)
fillStyleSets or returns the color, gradient, or pattern used to fill the drawing
lineCapSets or returns the style of the end caps for a line
lineJoinSets or returns the type of corner created, when two lines meet
lineWidthSets or returns the current line width
miterLimitSets or returns the maximum miter length
shadowBlurSets or returns the blur level for shadows
shadowColorSets or returns the color to use for shadows
shadowOffsetXSets or returns the horizontal distance of the shadow from the shape
shadowOffsetYSets or returns the vertical distance of the shadow from the shape
strokeStyleSets or returns the color, gradient, or pattern used for strokes

Transformations

MethodDescription
scale()Scales the current drawing bigger or smaller
rotate()Rotates the current drawing
translate()Remaps the (0,0) position on the canvas
transform()Replaces the current transformation matrix for the drawing
setTransform()Resets the current transform to the identity matrix. Then runs transform()

Image Drawing

MethodDescription
drawImage()Draws an image, canvas, or video onto the canvas

The ImageData Object / Pixel Manipulation

Method/PropertyDescription
createImageData()Creates a new, blank ImageData object
getImageData()Returns an ImageData object that copies the pixel data for the specified rectangle on a canvas
ImageData.dataReturns an object that contains image data of a specified ImageData object
ImageData.heightReturns the height of an ImageData object
ImageData.widthReturns the width of an ImageData object
putImageData()Puts the image data (from a specified ImageData object) back onto the canvas

Compositing

PropertyDescription
globalAlphaSets or returns the current alpha or transparency value of the drawing
globalCompositeOperationSets or returns how a new image are drawn onto an existing image

Other Methods

MethodDescription
clip()Clips a region of any shape and size from the original canvas
save()Saves the state of the current drawing context and all its attributes
restore()Restores the previously saved state and attributes
createEvent() 
getContext() 
toDataURL() 

Standard Properties and Events

The canvas object also supports the standard properties and events.


Related Pages

Canvas tutorial: Canvas Tutorial

HTML tutorial: HTML5 Canvas

HTML reference: HTML <canvas> tag


Browser Support

The <canvas> element is an HTML5 standard (2014).

Canvas API is supported in all modern browsers:

ChromeEdgeFirefoxSafariOperaIE
YesYesYesYesYes9-11

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.

close