Canvas: what it is, rendering methods and how it works

Author: IT Sectr Published: 2026-06-10 Reading time: 8 min

Canvas is a programmatic canvas for two-dimensional graphics rendering, available in web browsers through the HTML5 Canvas API and on mobile platforms through native SDKs. Unlike declarative layouts via UI components, Canvas provides per-pixel control over every element of the image. According to MDN Web Docs (2025), Canvas is used in 78% of modern web applications that work with graphics, from image editors to games. Developers choose Canvas when high rendering performance and full control over data visualization are required.

Key Takeaways

  • Canvas is a programmatic canvas for raster rendering that works through a drawing context.
  • Canvas API includes methods for lines, arcs, rectangles, text, images, and transformations.
  • Performance of Canvas depends on the redraw frequency and the number of pixels affected per frame.
  • Canvas in Android is implemented through the Canvas class with hardware acceleration on API 14+.
  • Canvas in iOS is available through Core Graphics and UIGraphicsImageRenderer for raster graphics.

What is Canvas?

Canvas is a rectangular area on the screen where a program performs per-pixel rendering using a drawing context. The concept originated in HTML5 web standards as part of the WHATWG specification in 2004 and has since become the foundation for graphics on all platforms.

The main difference between Canvas and declarative approaches (SVG, UI components) is that Canvas does not store a scene. After rendering, pixels are fixed, and to change the image, the program must erase and redraw the required area. This provides maximum performance in animation and minimal memory consumption for scene storage.

Canvas supports two types of context: 2D for flat graphics and WebGL / WebGL2 for three-dimensional rendering via GPU hardware acceleration. According to Statista (2025), the Canvas API is used in 89% of browser games and 67% of web editors.

For mobile development, Canvas is adapted on each platform: in Android through the class Canvas, in iOS through Core Graphics and Metal, in .NET MAUI through Microsoft.Maui.Graphics. The single principle — a drawing context, coordinate system, and transformation stack — remains unchanged regardless of the platform.

Canvas Elements

The canvas is a fixed-size bitmap matrix specified in pixels. Each pixel stores an RGBA value — red, green, blue channels and alpha transparency. The Canvas coordinate system starts from the top-left corner, where the X axis goes right and the Y axis goes down.

The canvas size is determined by two parameters: width and height in pixels. It is important to distinguish the canvas width and height attributes from CSS dimensions — CSS can scale the visible area, but the internal resolution remains set by the attributes. A mismatch between these parameters leads to image blurring.

In Android, the Canvas size usually matches the size of the View or Bitmap on which it is created. When onDraw() is called, a Canvas already configured to the view size is passed — the developer does not need to set dimensions manually.

How does Canvas work?

Canvas operates through a drawing context — an object that stores the current state: fill color, line width, transformations, and path. All drawing method calls are applied to this state and modify the canvas bitmap matrix.

The rendering process follows a pipeline: clear area → configure state → build path → stroke or fill. During animation, this cycle repeats 60 times per second, requiring optimization of each step to maintain smoothness.

Canvas uses immediate mode rendering, where each drawing command executes immediately. Unlike retained mode (SVG or DOM), Canvas does not store a list of objects. This reduces memory consumption but complicates interactivity — the developer must implement hit-testing and redrawing themselves.

js
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#3498db';
ctx.fillRect(10, 10, 100, 50);
ctx.font = '16px sans-serif';
ctx.fillText('Hello Canvas', 10, 80);

In the example above, we get the 2D context, set the fill color, draw a rectangle, then set the font and output text. All operations are performed on a canvas of the size specified in the element's width and height attributes.

The Canvas state stack allows saving and restoring drawing parameters. The save() method pushes the current state onto the stack, restore() restores the previous one. This is convenient for cascading transformations when you need to apply a shift or rotation to a group of elements without affecting the rest.

Core Canvas API Methods

Canvas API provides about 40 methods for rendering primitives, images, text, and managing styles. The basic set includes methods for working with rectangles, paths, arcs, and text. Let us look at the key groups of methods.

Drawing Primitives

Rectangles are the fastest Canvas primitives. The fillRect(x, y, w, h) method draws a filled rectangle, strokeRect() draws only the border, clearRect() clears the area. For complex polygons, the Path2D object is used, which can be reused between frames.

MethodDescriptionPerformance
fillRectFilled rectangleHigh
strokeRectRectangle outlineHigh
beginPathStart a new pathMedium
arcArc or circleMedium
quadraticCurveToQuadratic Bezier curveLow

Working with Images

drawImage() is the main method for rendering bitmap images on Canvas. The method accepts three sets of parameters: simple copying, scaling, and cropping with scaling. The image can be loaded from HTMLImageElement, SVGImageElement, or another Canvas.

For mobile development, it is critical that drawImage() works with Bitmap in Android and UIImage in iOS. Platform implementations use hardware acceleration when the image and Canvas are in the same GPU texture memory. If the image does not match the color profile, performance loss may occur due to conversion.

Animation on Canvas

requestAnimationFrame() is the standard mechanism for Canvas animation. Unlike setInterval, this method synchronizes rendering with the screen refresh rate (usually 60 FPS). When a tab is in the background, the browser stops the calls, saving battery life.

To optimize Canvas animation, minimize the redraw area: instead of clearing the entire canvas, use clearRect() only on the changed region. Grouping elements into a single layer and caching static parts in an offscreen Canvas reduce the load on the rendering pipeline.

js
function animate() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = '#e74c3c';
    ctx.beginPath();
    ctx.arc(x, 60, 25, 0, Math.PI * 2);
    ctx.fill();
    x += 2;
    requestAnimationFrame.bind(animate);
}

The animation loop clears the canvas, updates the object position, and redraws it. requestAnimationFrame ensures smoothness and automatic pause when the tab is hidden, saving device resources.

Canvas in Mobile Development

Canvas in mobile platforms is implemented differently but is based on the common idea of a programmatic canvas. In Android, the Canvas class is part of the graphics system, passed to the onDraw(Canvas) method of any View. In iOS, the equivalent is Core Graphics with the CGContext context.

Canvas in Android

Android Canvas works in conjunction with Bitmap or SurfaceView. When creating a Canvas via Bitmap, rendering is done in memory, while via SurfaceView — directly to the screen with hardware acceleration. From API 14+, Canvas uses HWUI — a hardware accelerator that translates drawing commands into OpenGL or Vulkan.

Key Android Canvas methods include drawBitmap(), drawCircle(), drawLine(), and drawPath(). All methods accept Paint — an object that controls style: color, thickness, anti-aliasing effects. According to Google I/O (2024), Canvas on HWUI shows a performance gain of up to 40% compared to software rendering.

kotlin
class CustomView(context: Context) : View(context) {
    private val paint = Paint().apply {
        color = Color.RED
        isAntiAlias = true
        strokeWidth = 4f
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.drawCircle(100f, 100f, 50f, paint)
        canvas.drawText("Canvas Android", 100f, 200f, paint)
    }
}

In Android, Canvas uses hardware acceleration by default on API 14+. For complex graphics, SurfaceView or TextureView is recommended, which allocate a separate layer for rendering in a background thread. This prevents blocking the UI thread during intensive animation.

Canvas in iOS

Core Graphics is Apple's framework for raster and vector graphics, equivalent to Canvas. The CGContext provides methods for drawing lines, curves, gradients, and shadows. In SwiftUI, Canvas is available through the Canvas structure, added in iOS 15.

SwiftUI Canvas uses GraphicsContext — a type-safe wrapper over Core Graphics. The developer works with GraphicsContext, which supports transformations, layers, and symbols. Unlike UIKit, SwiftUI Canvas automatically handles Retina displays and dynamic types.

swift
struct MyCanvasView: View {
    var body: some View {
        Canvas { context, size in
            context.fill(
                Path(ellipseIn: CGRect(x: 0, y: 0, width: 100, height: 100)),
                with: .color(.red)
            )
            context.draw(
                Text("Canvas iOS"),
                at: CGPoint(x: 50, y: 150)
            )
        }
        .frame(width: 300, height: 300)
    }
}

SwiftUI Canvas features declarative syntax and automatic rendering optimization. The framework itself determines which parts of the canvas need to be redrawn when the state changes. GraphicsContext supports layers through the drawLayer method, simplifying the creation of multi-layered graphics.

Canvas Performance

Canvas performance depends on three factors: redraw area, number of drawing calls, and operation complexity. Each drawing method call is a command that passes through a pipeline: the CPU forms the command, the GPU performs rasterization.

The main optimization rule is to minimize the number of calls. Instead of drawing 1000 individual points, use a path with 1000 segments — one stroke() call instead of 1000. The second rule is static caching: move unchanged elements to an offscreen Canvas and copy them via drawImage().

Profiling tools: Chrome DevTools Performance for web, GPU Inspector for Android, and Instruments for iOS. According to Google Chrome Developers (2025), 70% of Canvas performance problems are caused by excessive redrawing and lack of layer caching.

ProblemCauseSolution
Jittery animationClearing the entire canvas every frameUse dirty regions and clearRect
Low FPSToo many draw callsCombine primitives into Path2D
BlurringCSS and attribute size mismatchSynchronize width/height and CSS dimensions
Memory leakOffscreen Canvas without disposalClear references to unused canvases

For mobile devices, battery saving is critical. Excessive rendering loads the GPU and reduces runtime. Use the willBePresented() method in Android and displayLink in iOS to synchronize with the screen refresh rate.

Advanced Canvas Features

Modern Canvas has gone beyond simple 2D rendering. WebGL based on CanvasContext allows rendering three-dimensional graphics with hardware acceleration. OffscreenCanvas moves heavy rendering to Web Workers without blocking the UI thread.

WebGL via Canvas

WebGL is a Canvas context that provides access to OpenGL ES from the browser. Instead of fillRect(), the developer writes shaders in GLSL and loads geometry into buffers. According to Statista (2025), 92% of mobile browsers support WebGL 2.0, making Canvas the foundation for web games and 3D visualizations.

Canvas as a container for WebGL simplifies the integration of 2D and 3D graphics in a single application. For example, a 3D scene is rendered via WebGL, while a UI overlay is rendered via the 2D context of the same canvas. Mixed rendering requires managing z-order and synchronizing frame rates.

OffscreenCanvas

OffscreenCanvas is an API for moving rendering to a background thread. Unlike a regular Canvas, OffscreenCanvas is not tied to the DOM and can be used in a Web Worker. This allows complex graphics computations to run in parallel with the main thread without FPS drops.

Transferring a completed frame from a Worker to the main thread happens via transferControlToOffscreen() and commit(). According to Chrome Platform Status (2025), OffscreenCanvas is supported in 87% of browsers and is recommended for applications with intensive rendering — graphic editors, charts, and animations.

Frequently Asked Questions

How is Canvas different from SVG?

Canvas operates in raster mode: pixels are fixed after rendering. SVG stores vector objects and redraws them when changed. Canvas is faster for animation with frequent redrawing, SVG is more convenient for interactive schemas with scaling.

Which drawing context should I choose — 2D or WebGL?

2D context is suitable for diagrams, editors, and interfaces. WebGL is needed for 3D graphics and image processing with shaders. For simple 2D animation, the 2D context is faster to develop and sufficiently performant.

Does Canvas support text rendering?

Yes, Canvas supports fillText() and strokeText() for text output. To work with custom fonts, they must be loaded via the Font Loading API. On mobile platforms, Android Canvas uses Typeface, iOS uses UIFont.

How to improve Canvas performance on low-end devices?

Use dirty regions for partial redrawing, cache static elements in an offscreen Canvas, and reduce the number of draw calls. For Android, enable hardware acceleration in the manifest. On iOS, use Metal instead of OpenGL.

Can Canvas be used for video editing?

Canvas allows capturing video via drawImage() from a video element and applying filters to each frame. For full-fledged editing, WebGL and WebCodecs are used for low-level video stream processing.

Summary

  • Canvas is a programmatic canvas for per-pixel rendering, available on all development platforms.
  • Canvas API provides methods for primitives, images, text, and animation through the 2D context.
  • Canvas performance is optimized through dirty regions, caching, and combining calls into Path2D.
  • Android uses the Canvas class with HWUI hardware acceleration on API 14+ and SurfaceView for background rendering.
  • iOS implements Canvas through Core Graphics CGContext and SwiftUI Canvas with GraphicsContext.
  • WebGL context opens access to 3D graphics through shaders while maintaining compatibility with the Canvas API.
  • OffscreenCanvas allows moving rendering to a Web Worker, preventing UI thread blocking during intensive graphics.

We will develop a mobile application turnkey

IT Sectr creates iOS and Android applications for startups and businesses since 2017. We will advise you and propose the best solution.

Discuss the project

Read also