HTML Canvas Manipulating Images

Beginner
10 min read
Updated: Nov 2026
5 examples
Live preview

Definition

On an <canvas>, images are painted with drawImage(). Sources can be an HTMLImageElement, another canvas, a video frame, ImageBitmap, and more.

Two common workflows: geometry (place, scale, crop with drawImage) and pixels (read/edit RGBA with getImageData / putImageData). Always wait for external images to load before drawing.

Baseline · Widely available.

drawImage, getImageData, and putImageData are stable Canvas 2D features across modern browsers since about July 2015.

Security · Tainted canvas.

Drawing a cross-origin image without CORS permission taints the canvas. Then getImageData, toDataURL, and toBlob throw. Prefer same-origin assets or set crossOrigin = "anonymous" when the host allows it.

Syntax

images.js
// Place
ctx.drawImage(image, dx, dy);

// Scale
ctx.drawImage(image, dx, dy, dWidth, dHeight);

// Crop source, then scale into destination
ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);

// Pixel edit
const data = ctx.getImageData(0, 0, w, h);
// … change data.data[i] …
ctx.putImageData(data, 0, 0);

For a URL-based Image(), draw inside the load listener (or after decode()).

Key Methods

Core image and pixel tools:

Method / paramDescriptionTry it
drawImage(img, dx, dy)Draw at destination top-leftTry it
drawImage(img, dx, dy, dw, dh)Scale to destination sizeTry it
drawImage(… 9 args)Crop source rect, draw into dest rectTry it
getImageData(x, y, w, h)Copy RGBA pixels into an ImageDataTry it
putImageData(data, dx, dy)Write pixel buffer back to the canvasTry it
createImageData(w, h)Blank ImageData (transparent black)see pixels

Global Attributes

The <canvas> tag also supports the Global Attributes in HTML.

Live Preview

A generated sample image is drawn with drawImage. Change scale or apply a pixel effect.

100%

Sample source is another canvas (same-origin), so pixel reads stay safe.

Canvas

drawImage + original

HTML Examples

Short, copy-ready snippets. Examples use another canvas as the image source so they run without external files. Use Try It Yourself for a live editor.

Example 1 — Place with drawImage

Build a small source canvas, then draw it at (dx, dy).

HTML
<canvas id="demo" width="300" height="160" aria-label="Place image with drawImage"></canvas>
<script>
  const ctx = document.getElementById("demo").getContext("2d");

  const src = document.createElement("canvas");
  src.width = 140;
  src.height = 90;
  const s = src.getContext("2d");
  s.fillStyle = "#2563eb";
  s.fillRect(0, 0, 140, 90);
  s.fillStyle = "#facc15";
  s.beginPath();
  s.arc(70, 45, 28, 0, Math.PI * 2);
  s.fill();

  ctx.fillStyle = "#f1f5f9";
  ctx.fillRect(0, 0, 300, 160);
  ctx.drawImage(src, 80, 35);
</script>
Try It Yourself

How It Works

  1. Create a source (here, an offscreen canvas with a blue rect and yellow circle).
  2. Paint the source before using it as an image.
  3. Clear/fill the target so placement is easy to see.
  4. Call drawImage(src, 80, 35) to place the top-left corner.

Example 2 — Scale with Width & Height

Use the 5-argument form to resize while drawing.

HTML
<canvas id="demo" width="300" height="160" aria-label="Scaled drawImage"></canvas>
<script>
  const ctx = document.getElementById("demo").getContext("2d");

  const src = document.createElement("canvas");
  src.width = 100;
  src.height = 60;
  const s = src.getContext("2d");
  s.fillStyle = "#16a34a";
  s.fillRect(0, 0, 100, 60);
  s.fillStyle = "#fff";
  s.font = "bold 16px sans-serif";
  s.fillText("SRC", 28, 38);

  ctx.fillStyle = "#f1f5f9";
  ctx.fillRect(0, 0, 300, 160);
  ctx.drawImage(src, 40, 30, 220, 100);
</script>
Try It Yourself

How It Works

  1. Source size is 100×60.
  2. Destination size is 220×100 via dWidth / dHeight.
  3. Aspect ratio can stretch if you pick mismatched sizes.
  4. Upscaling can look soft; see imageSmoothingEnabled for control.

Example 3 — Crop (Slice) Then Draw

Nine arguments: source rectangle, then destination rectangle.

HTML
<canvas id="demo" width="300" height="160" aria-label="Cropped drawImage slice"></canvas>
<script>
  const ctx = document.getElementById("demo").getContext("2d");

  const src = document.createElement("canvas");
  src.width = 200;
  src.height = 120;
  const s = src.getContext("2d");
  s.fillStyle = "#7c3aed";
  s.fillRect(0, 0, 100, 120);
  s.fillStyle = "#ea580c";
  s.fillRect(100, 0, 100, 120);
  s.fillStyle = "#fff";
  s.font = "bold 14px sans-serif";
  s.fillText("L", 40, 65);
  s.fillText("R", 140, 65);

  ctx.fillStyle = "#f1f5f9";
  ctx.fillRect(0, 0, 300, 160);
  // Take only the right half (sx=100), enlarge into destination
  ctx.drawImage(src, 100, 0, 100, 120, 70, 20, 160, 120);
</script>
Try It Yourself

How It Works

  1. Source rect: (sx, sy, sWidth, sHeight) = right half.
  2. Dest rect: (dx, dy, dWidth, dHeight) places and scales that slice.
  3. Useful for sprites packed into one sheet.
  4. Only orange “R” appears enlarged — purple “L” is cropped out.

Example 4 — Grayscale Pixels

Read RGBA bytes, average channels, write them back.

HTML
<canvas id="demo" width="300" height="160" aria-label="Grayscale with getImageData"></canvas>
<script>
  const canvas = document.getElementById("demo");
  const ctx = canvas.getContext("2d");

  const src = document.createElement("canvas");
  src.width = 220;
  src.height = 100;
  const s = src.getContext("2d");
  const g = s.createLinearGradient(0, 0, 220, 0);
  g.addColorStop(0, "#2563eb");
  g.addColorStop(0.5, "#16a34a");
  g.addColorStop(1, "#ea580c");
  s.fillStyle = g;
  s.fillRect(0, 0, 220, 100);

  ctx.drawImage(src, 40, 30);
  const imageData = ctx.getImageData(40, 30, 220, 100);
  const data = imageData.data;
  for (let i = 0; i < data.length; i += 4) {
    const avg = (data[i] + data[i + 1] + data[i + 2]) / 3;
    data[i] = data[i + 1] = data[i + 2] = avg;
  }
  ctx.putImageData(imageData, 40, 30);
</script>
Try It Yourself

How It Works

  1. Draw first so pixels exist on the canvas.
  2. getImageData copies that region into a buffer.
  3. Loop by 4 (R, G, B, A). Set R=G=B to the average.
  4. putImageData paints the edited buffer back.

Example 5 — Invert Colors

Subtract each channel from 255 for a photo-negative look.

HTML
<canvas id="demo" width="300" height="160" aria-label="Invert colors with putImageData"></canvas>
<script>
  const canvas = document.getElementById("demo");
  const ctx = canvas.getContext("2d");

  const src = document.createElement("canvas");
  src.width = 220;
  src.height = 100;
  const s = src.getContext("2d");
  s.fillStyle = "#2563eb";
  s.fillRect(0, 0, 110, 100);
  s.fillStyle = "#facc15";
  s.fillRect(110, 0, 110, 100);

  ctx.drawImage(src, 40, 30);
  const imageData = ctx.getImageData(40, 30, 220, 100);
  const data = imageData.data;
  for (let i = 0; i < data.length; i += 4) {
    data[i] = 255 - data[i];
    data[i + 1] = 255 - data[i + 1];
    data[i + 2] = 255 - data[i + 2];
  }
  ctx.putImageData(imageData, 40, 30);
</script>
Try It Yourself

How It Works

  1. Draw a two-tone source (blue + yellow).
  2. Read pixels with getImageData.
  3. Invert RGB: 255 - channel (leave alpha alone).
  4. Write back with putImageData — yellow becomes dark blue-ish, blue becomes yellow-ish.

Edge Cases & Pitfalls

Most image bugs are load timing, CORS, or confusing the crop arguments.

load

Draw after load

For new Image() / <img>, call drawImage in the load handler (or after decode()). Drawing too early often paints nothing.

cors

Tainted canvas blocks pixels

Cross-origin images without CORS break getImageData / export. Use same-origin files or proper crossOrigin + server headers.

args

9-arg order matters

Source crop first (sx…sHeight), then destination (dx…dHeight). Swapping them crops the wrong region.

size

Bitmap vs CSS size

HTML width/height set the bitmap. CSS-only sizing scales the display and can blur images.

smooth

Scaling quality

imageSmoothingEnabled (default true) softens scaled images. Set false for a pixelated look when zooming sprites.

Browser Support

drawImage and ImageData APIs are part of Canvas 2D in every modern browser.

✓ Baseline · Widely available

drawImage & ImageData

Widely available since about July 2015. Chrome, Firefox, Safari, Edge, and Opera support placing, scaling, cropping, and pixel read/write. Internet Explorer 9+ supports the core methods.

98% Global support (approx.)
Google Chrome All modern
Full support
Mozilla Firefox All modern
Full support
Apple Safari All modern
Full support
Microsoft Edge All modern
Full support
Opera All modern
Full support
Samsung Internet All modern
Full support
Internet Explorer 9+
Supported
drawImage / getImageData Widely supported

Bottom line: Safe for production image drawing and same-origin pixel edits on Canvas 2D everywhere modern browsers run.

Key Takeaways

  • Place / scale / crop: 3-, 5-, or 9-arg drawImage.
  • Pixels: getImageData → edit RGBA → putImageData.
  • Wait for load when using URL-based images.
  • CORS: tainted canvas blocks pixel reads and exports.

One line: ready source → drawImage → optional pixel loop.

Default CSS Settings

Image drawing is a Canvas API concern. The <canvas> element still uses typical user-agent CSS:

default.css
canvas {
  display: inline;
}

Set bitmap size with HTML width/height. CSS-only sizing scales the bitmap and can blur drawn images.

Frequently Asked Questions

Load or create a source (HTMLImageElement, another canvas, video frame, etc.), wait until it is ready, then call ctx.drawImage(source, dx, dy) or a scaled/cropped overload.
3 arguments place the image; 5 arguments also set destination width/height (scale); 9 arguments crop a source rectangle then draw it into a destination rectangle.
Cross-origin images without CORS permission taint the canvas. Same-origin or CORS-allowed sources (and crossOrigin = "anonymous" when the server allows it) keep pixel reads working.
drawImage the source, getImageData, average each pixel’s R/G/B (or use a weighted average), write those values back, then putImageData.
Yes. HTMLCanvasElement is a valid drawImage source. Paint the source canvas first, then drawImage it onto the target.
Always wait when using Image() or <img> with a URL. Drawing before load often does nothing; older browsers may throw.

Next: Transforms

Browse translate, rotate, and scale hubs, then open each guide.

Transforms →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful