问题描述
有什么方法可以使 CanvasGradient
重复吗?
Is there any way to make a CanvasGradient
that repeats?
我认为没有,因为我没有在 CanvasRenderingContext2D.createLinearGradient
或 createRadialGradient
或 CanvasGradient
这将适用
I assume not, because I don't see any options on CanvasRenderingContext2D.createLinearGradient
or createRadialGradient
or any properties on CanvasGradient
that would apply
但是我真的很惊讶,因为CSS3支持重复线性渐变
和重复径向渐变
背景样式.
But I'm really surprised this feature would be missing given that CSS3 supports repeating-linear-gradient
and repeating-radial-gradient
background styles.
我已经找到了一种解决方法,可以使用 CanvasRenderingContext2D.createPattern
重复线性渐变(请参见下面的答案),但是不是一种重复径向渐变的方法.
I have figured out a workaround for repeating linear gradients using CanvasRenderingContext2D.createPattern
(see my answer below) but not a way to make a repeating radial gradient.
推荐答案
对于线性渐变,可以从渐变的单位矩形创建图案:
For a linear gradient it's possible to create a pattern from the unit rectangle of the gradient:
var tile = document.createElement('canvas')
tile.width = tile.height = 10
var tileCtx = tile.getContext('2d')
var gradient = tileCtx.createLinearGradient(0, 0, tile.width, tile.height)
gradient.addColorStop(0, 'red')
gradient.addColorStop(0.25, 'red')
gradient.addColorStop(0.25, 'blue')
gradient.addColorStop(0.5, 'blue')
gradient.addColorStop(0.5, 'red')
gradient.addColorStop(0.75, 'red')
gradient.addColorStop(0.75, 'blue')
gradient.addColorStop(1, 'blue')
tileCtx.fillStyle = gradient
tileCtx.fillRect(0, 0, 10, 10)
var canvas = document.createElement('canvas')
canvas.width = canvas.height = 200
canvas.style.width = canvas.style.height = '200px'
document.body.appendChild(canvas)
var context = canvas.getContext('2d')
context.fillStyle = context.createPattern(tile, 'repeat')
context.fillRect(0, 0, 200, 200)
但是,我不知道重复进行径向渐变的方法.
However, I don't know of a way to make a repeating radial gradient.
这篇关于如何制作重复的CanvasGradient的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!