Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AWS AI GO KOTLIN SASS VUE GEN AI CYBERSECURITY DATA SCIENCE
     ❯   

HTML Canvas Gradients


Canvas - Gradients

Gradients can be used to fill rectangles, circles, lines, text, etc. Shapes on the canvas are not limited to solid colors.

There are two different types of gradients:

  • createLinearGradient(x,y,x1,y1) - creates a linear gradient
  • createRadialGradient(x,y,r,x1,y1,r1) - creates a radial/circular gradient

Once we have a gradient object, we must add two or more color stops.

The addColorStop() method specifies the color stops, and its position along the gradient. Gradient positions can be anywhere between 0 to 1.

To use the gradient, set the fillStyle or strokeStyle property to the gradient, then draw the shape (rectangle, text, or a line).


Using createLinearGradient()

Example

Create a linear gradient. Fill rectangle with the gradient:

Your browser does not support the HTML5 canvas tag.

JavaScript:

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

// Create gradient
const grd = ctx.createLinearGradient(0, 0, 200, 0);
grd.addColorStop(0, "red");
grd.addColorStop(1, "white");

// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(10, 10, 150, 80);
Try it Yourself »


Using createRadialGradient():

Example

Create a radial/circular gradient. Fill rectangle with the gradient:

Your browser does not support the HTML5 canvas tag.

JavaScript:

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

// Create gradient
const grd = ctx.createRadialGradient(75, 50, 5, 90, 60, 100);
grd.addColorStop(0, "red");
grd.addColorStop(1, "white");

// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(10, 10, 150, 80);
Try it Yourself »

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-2023 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.