Styles Gradients 过渡色 - caleb531/jcanvas-docs GitHub Wiki
Gradients 过渡色
The createGradient()
method returns a canvas gradient object, which is used as a fill or stroke style.
createGradient()
方法返回一个画布过渡色对象,它可以用作填充或描边(笔触)。
Gradient colors are defined using c1
, c2
, c3
, and so on. Optional color stops are defined using s1
, s2
, s3
, and so on (and can be any number from 0 through 1).
过渡色使用c1
,c2
,c3
等等来定义。可以选择使用s1
,s2
,s3
(可以是0到1之间的任何数字)等等来定义色彩停点。
Linear 线性过渡
var linear = $('canvas').createGradient({
x1: 0, y1: 20,
x2: 0, y2: 80,
c1: 'rgb(0, 0, 0)',
c2: '#0f0',
c3: 'blue'
});
$('canvas').drawArc({
fillStyle: linear,
x: 50, y: 50,
radius: 30
});
var linear = $('canvas').createGradient({
x1: 0, y1: 20,
x2: 0, y2: 80,
c1: 'rgb(0, 0, 0)',
c2: '#0f0', s2: 0.2,
c3: 'blue', s3: 0.5
});
$('canvas').drawArc({
fillStyle: linear,
x: 50, y: 50,
radius: 30
});
Radial 径向过渡
Radial gradients are created when the r1
or r2
properties are defined.
径向过渡是使用定义r1
或r2
属性来创建的。
var radial = $('canvas').createGradient({
x1: 50, y1: 50,
x2: 50, y2: 50,
r1: 10, r2: 30,
c1: 'rgba(255, 0, 0, 0.75)',
c2: '#000'
});
$('canvas').drawArc({
fillStyle: radial,
x: 50, y: 50,
radius: 30
});
Animating Layers with Gradients 使用过渡色动态化层
There are cases where you may wish to animate a layer that has a gradient fill/stroke. However, animating the layer's position or size will leave the gradient unaffected, because gradients are relative to the canvas.
有些时候你想要使用过渡色填充或笔触来动态化层,但动态化层的定位或尺寸,会保留过渡色不受影响。因为过渡色是基于画布的。
To demonstrate this behavior, consider the following example:
为了演示这个行为,思考下边的例子:
// Create and store a linear gradient 创建并保存一个线性过渡
var gradient = $('canvas').createGradient({
// Gradient is drawn relative to layer position 过渡相对于层位置绘制
x1: 0, y1: 20,
x2: 0, y2: 140,
c1: '#36c', c2: '#c33'
});
// Create layer with gradient fill 创建一个使用过渡色填充的层
$('canvas').drawRect({
layer: true,
name: 'box',
fillStyle: gradient,
x: 100, y: 80,
width: 100, height: 60
});
// Animate layer 动态化层
$('canvas').animateLayer('box', {
x: 220, y: 150
}, 1000);
To solve this problem, by using a function as the layer's fill/stroke style, you can achieve a gradient which moves with its layer. Note that the below example assumes that the gradient's coordinates are relative to the layer's size and position.
为了解决这个问题,可以使用一个函数作为层的填充/描边样式,你可以达成过渡色随着层移动的效果。注意,下边的代码假设,过渡色坐标相对于层的尺寸和位置。
// Create layer with gradient fill 创建带有过渡填充的层
$('canvas').drawRect({
layer: true,
name: 'box',
// Define fill as a function 定义填充函数
fillStyle: function(layer) {
return $(this).createGradient({
// Gradient is drawn relative to layer position 过渡色相对于层位置绘制
x1: 0, y1: layer.y - layer.height,
x2: 0, y2: layer.y + layer.height,
c1: '#36c', c2: '#c33'
});
},
x: 100, y: 80,
width: 100, height: 60
});
// Animate layer 动态化层
$('canvas').animateLayer('box', {
x: 220, y: 150
}, 1000);
Notes 注意
Color stops are optional, and are measured from 0 to 1.
色彩停点是可选的,它们以0到1之间的值衡量。