JavaScript Canvas - Gradient & Pattern Fills
Written by Ian Elliot   
Monday, 25 October 2021
Article Index
JavaScript Canvas - Gradient & Pattern Fills
Algorithm for a Radial Gradient Fill
Pattern Fills

Pattern Fills

The final type of fill that you can use is a pattern or bitmap fill. This is easy to understand and easy to use. You need to create a pattern before you use it:

ctc.createPattern(image, repeat);

To fill an arbitrary object the pattern specified by the image is likely to need to be repeated and the repeat parameter is a string that determines how this is done: 

  • "repeat" (both directions)

  • "repeat-x" (horizontal only)

  • "repeat-y" (vertical only)

  • "no-repeat" (neither direction) 

The default is repeat.

The source of the pattern can be any of: 

  • HTMLImageElement (<img>)

  • SVGImageElement (<image>)

  • HTMLVideoElement (<video>)

  • HTMLCanvasElement (<canvas>)

  • ImageBitmap

  • OffscreenCanvas 

Some of these are obvious and some are described in later chapters. The biggest problem in using many of these sources is knowing when they are ready to be used. For example:

var img = new Image();
img.src = 'url of graphics file';
var pattern = ctx.createPattern(img, 'repeat');
ctx.fillStyle = pattern;
ctx.fillRect(0, 0, 300, 300);

This is a very standard way of loading a bitmap without involving any markup. The Image object starts to download the file as soon as its src property is set to a URL but it does this in the background. You cannot simply continue and use the image as if it was downloaded – sometimes you might be lucky, other times strange things will happen.

The correct way to do the job is to use the onload event to wait until the file has loaded:

var img = new Image();
img.src = 'url of graphics file';
img.onload = function() {
  var pattern = ctx.createPattern(img, 'repeat');
  ctx.fillStyle = pattern; 
  ctx.fillRect(0, 0, 300, 300);

This is easy enough, but notice that now the rest of your graphics code has to be in the callback function and this is a nuisance. There are better ways to organize the code using promises or using async and await, but an even better idea is to avoid asynchronously loading bitmaps wherever possible. For example, if we place the graphic in the page using an <img> tag with id bitmap1 then we can use it as a pattern source:

var img = document.getElementById('bitmap1');
  var pattern = ctx.createPattern(img, 'repeat');
  ctx.fillStyle = pattern;
  ctx.fillRect(0, 0, 300, 300);

The window.onload event only fires after all of the resources have loaded. In this case the advantage is that you would write your entire graphics program as the load event callback function. If you don’t want the image to be seen you can hide it.

Another way of avoiding an asynchronous load is to draw the pattern using another canvas or an Offscreencanvas (see later).

This only works if the pattern can be easily and quickly drawn:

var myPath = new Path2D();
myPath.moveTo(25, 0);
myPath.lineTo(50, 50);
myPath.lineTo(0, 50);
myPath.lineTo(25, 0);
var c1 = document.createElement("canvas");
c1.width = 50;
c1.height = 50;
var pattern = ctx.createPattern(c1, 'repeat');
ctx.fillStyle = pattern;
ctx.fillRect(0, 0, 800, 800);

Notice that the second canvas object doesn’t have to be added to the DOM and so doesn’t show.


There are many other ways of creating bitmaps suitable for use in patterns – see Chapter 8.


  • The stroke function simply colors the outline of the path, whereas fill colors all of the points in the interior of the path.

  • Color can be specified by name, RGB components or HSL.

  • Alpha values control the transparency of the color, with 1.0 being opaque and 0.0 being completely transparent.

  • For stroke you can set the lineWidth, lineCap, lineJoin and lineDash.

  • Anti-aliasing makes drawing look smoother, but it can cause unexpected results for small details. It cannot be disabled.

  • The simplest way of combining old and new colors is the painter’s algorithm, which allows the latest color to cover up the old.

  • Determining what is a “hole” in a closed path is difficult. There are two general rules, odd-even and non-zero winding, and they are both valid ways of defining a hole.

  • As well as solid color fills, you can also use linear gradient and radial gradient fills.

  • Pattern fills allow you to use any bitmap as a sort of “wallpaper” for the interior of paths.

Now available as a paperback or ebook from Amazon.

JavaScript Bitmap Graphics
With Canvas




  1. JavaScript Graphics
  2. Getting Started With Canvas
  3. Drawing Paths
      Extract: Basic Paths 
      Extract: Bezier Curves 
  4. Stroke and Fill
      Extract: Stroke Properties 
      Extract: Fill and Holes
      Extract: Gradient & Pattern Fills 
  5. Transformations
      Extract: Transformations
      Extract: Custom Coordinates 
      Extract  Graphics State
  6. Text
      Extract: Text, Typography & SVG 
      Extract: Unicode 
  7. Clipping, Compositing and Effects
      Extract: Clipping & Basic Compositing 
  8. Generating Bitmaps
      Extract:  Introduction To Bitmaps
      Extract :  Animation 
  9. WebWorkers & OffscreenCanvas
      Extract: Web Workers **NEW!
      Extract: OffscreenCanvas
  10. Bit Manipulation In JavaScript
      Extract: Bit Manipulation  
  11. Typed Arrays
  12. Files, blobs, URLs & Fetch
      Extract: Blobs & Files
      Extract: Read/Writing Local Files 
  13. Image Processing
      Extract: ImageData
      Extract: The Filter API
  14. 3D WebGL
      Extract: WebGL 3D 
  15. 2D WebGL
    Extract: WebGL Convolutions 







To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.





or email your comment to:


Last Updated ( Monday, 25 October 2021 )