search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

Table of Contents
Set the canvas size dynamically with JavaScript
Use a container to control layout
Handle high-DPI (retina) displays
Key points to remember
Home Web Front-end H5 Tutorial How to make an HTML5 canvas responsive

How to make an HTML5 canvas responsive

Aug 19, 2025 pm 04:28 PM

To make HTML5 Canvas responsiveness, its width and height attributes must be dynamically adjusted through JavaScript and the content can be redrawn. It cannot rely solely on CSS, otherwise it will cause blur or stretching; first set the width and height of the canvas to 100% to adapt to the container, and then get the display size through clientWidth and clientHeight, set canvas.width and canvas.height to this size to match the pixel resolution, and readjust when the window size changes. and redraw; to maintain the clarity under high DPI screen, devicePixelRatio needs to be calculated and applied to internal resolution, and coordinate system scaling is used using ctx.scale; finally, canvas is wrapped in a container with aspect height or aspect ratio limitations to control the layout, ensuring that it can be displayed correctly on different devices and the image is sharp. The complete responsive solution includes three key steps: dynamic sizing adjustment, content redrawing and DPI adaptation, which can be run stably in various screen environments after implementation.

How to make an HTML5 canvas responsive

Making an HTML5 canvas responsive isn't as straightforward as making other HTML elements responsive, because canvas rendering is based on pixel dimensions set via JavaScript or attributes, not just CSS. If you don't handle it properly, the canvas can appear blurry or stretched on different screen sizes. Here's how to make it work correctly.

Set the canvas size dynamically with JavaScript

The key to a responsive canvas is adjusting its drawing buffer (the actual pixel resolution) based on the container or viewport size. You can't rely solely on CSS to scale the canvas without losing quality.

Instead, use JavaScript to:

  • Set the canvas width and height attributes to match the desired display size in pixels.
  • Redraw the content whenever the window resizes.
 <canvas id="myCanvas"></canvas>
 #myCanvas {
  display: block;
  width: 100%;
  height: auto;
}
 const canvas = document.getElementById(&#39;myCanvas&#39;);
const ctx = canvas.getContext(&#39;2d&#39;);

function resizeCanvas() {
  // Set display size (CSS pixels)
  const displayWidth = canvas.clientWidth;
  const displayHeight = canvas.clientHeight;

  // Check if the canvas is not the same size
  const needResize = canvas.width !== displayWidth || canvas.height !== displayHeight;

  if (needResize) {
    // Set the actual size to match the display size
    canvas.width = displayWidth;
    canvas.height = displayHeight;
  }

  // Redraw your content
  drawContent();
}

function drawContent() {
  // Example: draw a rectangle
  ctx.fillStyle = &#39;blue&#39;;
  ctx.fillRect(0, 0, canvas.width, canvas.height);
}

// Initial setup
resizeCanvas();

// Handle window resize
window.addEventListener(&#39;resize&#39;, resizeCanvas);

Use a container to control layout

Wrap the canvas in a responsive container so you can control its aspect ratio or maximum size using CSS.

 
<canvas id="myCanvas"></canvas>
 .canvas-container {
  width: 100%;
  max-width: 800px;
  aspect-ratio: 16 / 9; /* Optional: maintain aspect ratio */
  margin: 0 auto;
}

#myCanvas {
  width: 100%;
  height: 100%;
  display: block;
}

This way, the canvas scales within the container, and JavaScript adjusts the internal resolution accordingly.

Handle high-DPI (retina) displays

On high-DPI screens (like Retina displays), you may need to scale the internal resolution to avoid blurry graphics.

 function getPixelRatio(context) {
  const backingStore = context.backingStorePixelRatio ||
                       context.webkitBackingStorePixelRatio ||
                       context.mozBackingStorePixelRatio ||
                       context.msBackingStorePixelRatio ||
                       context.oBackingStorePixelRatio ||
                       1;

  return (window.devicePixelRatio || 1) / backingStore;
}

function resizeCanvas() {
  const displayWidth = canvas.clientWidth;
  const displayHeight = canvas.clientHeight;

  const needResize = canvas.width !== displayWidth || canvas.height !== displayHeight;

  if (needResize) {
    const pixelRatio = getPixelRatio(ctx);

    // Set the internal size to include pixel ratio
    canvas.width = displayWidth * pixelRatio;
    canvas.height = displayHeight * pixelRatio;

    // Scale the context to ensure correct drawing coordinates
    ctx.scale(pixelRatio, pixelRatio);
  }

  drawContent();
}

This ensures sharp graphics on high-resolution screens by increasing the internal resolution while keeping the displayed size consistency.

Key points to remember

  • Never rely only on CSS to resize the canvas — it will stretch the image and cause blurriness.
  • Always match canvas.width and canvas.height to the desired display size in pixels.
  • Use clientWidth and clientHeight to get the actual on-screen size.
  • Call resizeCanvas() on window resize to keep it responsive.
  • For high-DPI screens, scale the internal resolution using devicePixelRatio .

Basically, responsive canvas = dynamic sizing redrawing DPI awareness. It takes a few extra steps, but once set up, it works reliably across devices.

The above is the detailed content of How to make an HTML5 canvas responsive. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Popular tool

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to create a progress bar for file uploads in HTML5? (Progress tag) How to create a progress bar for file uploads in HTML5? (Progress tag) Mar 06, 2026 am 02:22 AM

Why can't the tag directly display the upload progress? It is a read-only visual component. It does not listen to network requests and is not automatically bound to the upload process of XMLHttpRequest or fetch. If you put it in and don't update the value manually, it will always stop at 0%. What really drives it is the event monitoring in the upload logic you write yourself. A common mistake is to only monitor onload (upload completed) but miss upload.onprogress. XMLHttpRequest (not fetch) must be used to obtain real-time upload progress, because fetch does not expose the max attribute of the event in the upload phase and must be set to the file size (file.size

How to create a tooltip using only HTML5? (Title attribute) How to create a tooltip using only HTML5? (Title attribute) Mar 06, 2026 am 12:23 AM

The title attribute is not a tooltip component, but an accessibility prompt mechanism implemented by the browser. The behavior, style, and interaction are uncontrollable and are only suitable for simple scenarios such as pure information supplement.

How to center an image vertically in HTML5? (Layout techniques) How to center an image vertically in HTML5? (Layout techniques) Mar 07, 2026 am 02:05 AM

Flexbox is the most stable for centered images. The key is to set display:flex and align-items:center in the parent container and specify the height; using place-items:center for Grid is more concise; absolute positioning requires top:50% with transform:translateY(-50%); vertical-align is invalid for block-level centering.

How to create a simple offline web app with HTML5? (Application Cache) How to create a simple offline web app with HTML5? (Application Cache) Mar 06, 2026 am 02:16 AM

ApplicationCache has been completely abandoned and will be removed from Chrome 61, Firefox 72, and Safari 11.1. ServiceWorker must be used instead; the latter requires HTTPS, manual registration and cache control, and the path, scope, and life cycle must match exactly.

How to create a contact form with validation in HTML5? (Required attribute) How to create a contact form with validation in HTML5? (Required attribute) Mar 06, 2026 am 02:06 AM

required only verifies that it is not empty, not the format; type="email" or pattern must be used together; native verification is only triggered when submitting, not real-time; checkbox/radio/select/textarea has special behavior; the server must re-verify and clean empty values.

How to create a collapsible details section in HTML5? (Summary tag) How to create a collapsible details section in HTML5? (Summary tag) Mar 06, 2026 am 02:25 AM

Use and implement native folding area. HTML5 natively supports folding and expansion. It can work without JS. It is a container and a click area. The browser adds a small triangle by default. Click it to expand/collapse the content. A common mistake is to write a closing tag (for example), which must have a start and end tag, and must be the first child element of , otherwise the folding logic will fail. The default is the collapsed state; add the open attribute to expand it by default: you can put text, icons, and even text inside, but don't nest another one - some browsers have inconsistent behavior and do not support IE. Edge79, Chrome12, Firefox49, and Safari6 have good support.

How to use the dialog element for modals in HTML5? (Native popups) How to use the dialog element for modals in HTML5? (Native popups) Mar 06, 2026 am 01:26 AM

The element does not render by default, does not occupy the layout, and is not recognized by screen readers. It must explicitly set the open attribute or call showModal()/show() to activate; to close, you need to call close(), click mask or press Esc to monitor manually; the old version of Safari needs to be polyfilled or downgraded; form submission will not automatically close and must be intercepted and manually controlled.

How to preload video or audio content in HTML5? (Preload attribute) How to preload video or audio content in HTML5? (Preload attribute) Mar 06, 2026 am 01:59 AM

What are the values ​​of the preload attribute, and what are their effects? The preload of HTML5 is a suggestive attribute. The browser is not forced to comply with it, but it will affect the initial resource loading strategy. It has only three legal values: auto, metadata, none. auto: It is recommended that the browser downloads the entire media file (including audio and video data) as soon as possible, which is suitable for scenarios where users are likely to play it, such as carousel videos on the homepage; but it will waste bandwidth, especially on mobile terminals or under weak networks. metadata: only prefetch meta information such as duration, size, frame rate, cover image, etc., without loading the actual audio and video frames, which is a safe choice in most cases none: explicitly tell the browser "don't load it yet" and wait until the user triggers playback (such as clicking) before starting it

Related articles