📅  最后修改于: 2023-12-03 15:16:05.136000             🧑  作者: Mango
The fillStyle
property in JavaScript is used to set or return the fill color, gradient, or pattern used to fill shapes and text in a canvas element. It is a property of the 2D rendering context, accessed using the getContext('2d')
method of the <canvas>
element.
The fillStyle
property can be set to various types of values:
context.fillStyle = 'red';
You can set the fillStyle
to a color string value, such as 'red'
, 'blue'
, or 'rgba(255, 0, 0, 0.5)'
. This will fill the shapes or text with the specified color.
const gradient = context.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, 'red');
gradient.addColorStop(1, 'blue');
context.fillStyle = gradient;
You can also set the fillStyle
to a gradient object created using the createLinearGradient()
or createRadialGradient()
methods of the rendering context. This allows you to create smooth transitions between colors.
const image = new Image();
image.src = 'pattern.png';
image.onload = function() {
const pattern = context.createPattern(image, 'repeat');
context.fillStyle = pattern;
};
Additionally, you can set the fillStyle
to a pattern image using the createPattern()
method. This allows you to fill shapes or text with an image that repeats or covers the area.
Here's an example demonstrating the usage of fillStyle
property to fill a rectangle:
const canvas = document.getElementById('myCanvas');
const context = canvas.getContext('2d');
context.fillStyle = 'red';
context.fillRect(10, 10, 100, 100);
In this example, a canvas element with an id of myCanvas
is selected, the rendering context is obtained, and the fillStyle
is set to 'red'
. The fillRect()
method is then used to draw a filled rectangle with the specified fill color.
By utilizing the fillStyle
property, you can control the appearance of the filled shapes and text within the canvas element in JavaScript.
Note: The
fillStyle
property does not apply to strokes, it only affects the inside of shapes and text. To set the color, gradient, or pattern for strokes, you should use thestrokeStyle
property.
For more information, you can refer to the MDN web docs on fillStyle.