Canvas Linear Gradients
How to Create a Linear Gradient
To create a linear gradient, follow these steps
- canvas - Assigning the canvas element to a variable.
- ctx - Assigning the 2d rendering context to another variable by calling the
getContext('2d')
method. - grad - Creating a new CanvasGradient object using
createLinearGradient()
canvas method, then assigning it to a variable. - addColorStop() - Use
addColorStop()
canvas method to add a new color stop, defined by an offset and a color. - fillStyle - Use
fillStyle
canvas property to specify the gradient to use inside shapes (any shape). - fillRect() - Use
fillRect()
canvas method to draws a rectangle that is filled according to the currentfillStyle
.
Example
HTML Online Editor
<!DOCTYPE html>
<html lang="en-US">
<body>
<canvas id="point" width="210" height="110">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas = document.getElementById("point");
var ctx = canvas.getContext("2d");
// Create gradient
var grad = ctx.createLinearGradient(0, 0, 200, 0);
grad.addColorStop(0, "black");
grad.addColorStop(1, "gold");
// Fill with gradient
ctx.fillStyle = grad;
ctx.fillRect(0, 0, 200, 100);
</script>
</body>
</html>
Syntax
ctx.createLinearGradient(x0, y0, x1, y1)
Attributes Value
Value | Explanation |
---|---|
x0 | Specifies the x-axis coordinate of the start point. |
y0 | Specifies the y-axis coordinate of the start point. |
x1 | Specifies the x-axis coordinate of the end point. |
y1 | Specifies the y-axis coordinate of the end point. |
Reminder
Hi Developers, we almost covered 93% of Canvas Tutorials with examples for quick and easy learning.
We are working to cover every Single Concept in Canvas.
Please do google search for:
Join Our Channel
Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.
This channel is primarily useful for Full Stack Web Developer.