CanvasRenderingContext2D.createLinearGradient() - Web APIs 编辑

The CanvasRenderingContext2D.createLinearGradient() method of the Canvas 2D API creates a gradient along the line connecting two given coordinates.

This method returns a linear CanvasGradient. To be applied to a shape, the gradient must first be assigned to the fillStyle or strokeStyle properties.

Note: Gradient coordinates are global, i.e., relative to the current coordinate space. When applied to a shape, the coordinates are NOT relative to the shape's coordinates.

Syntax

CanvasGradient ctx.createLinearGradient(x0, y0, x1, y1);

The createLinearGradient() method is specified by four parameters defining the start and end points of the gradient line.

Parameters

x0
The x-axis coordinate of the start point.
y0
The y-axis coordinate of the start point.
x1
The x-axis coordinate of the end point.
y1
The y-axis coordinate of the end point.

Return value

CanvasGradient
A linear CanvasGradient initialized with the specified line.

Examples

Filling a rectangle with a linear gradient

This example initializes a linear gradient using the createLinearGradient() method. Three color stops between the gradient's start and end points are then created. Finally, the gradient is assigned to the canvas context, and is rendered to a filled rectangle.

HTML

<canvas id="canvas"></canvas>

JavaScript

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

// Create a linear gradient
// The start gradient point is at x=20, y=0
// The end gradient point is at x=220, y=0
var gradient = ctx.createLinearGradient(20,0, 220,0);

// Add three color stops
gradient.addColorStop(0, 'green');
gradient.addColorStop(.5, 'cyan');
gradient.addColorStop(1, 'green');

// Set the fill style and draw a rectangle
ctx.fillStyle = gradient;
ctx.fillRect(20, 20, 200, 100);

Result

Specifications

SpecificationStatusComment
HTML Living Standard
The definition of 'CanvasRenderingContext2D.createLinearGradient' in that specification.
Living Standard 

Browser compatibility

BCD tables only load in the browser

Gecko-specific notes

  • Starting with Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1), specifying non-finite values now throws NOT_SUPPORTED_ERR instead of SYNTAX_ERR.

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:49 次

字数:5325

最后编辑:6年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文