Is there any way to make a CanvasGradient
that repeats?
I assume not, because I don't see any options on CanvasRenderingContext2D.createLinearGradient
or createRadialGradient
or any properties on CanvasGradient
that would apply
But I'm really surprised this feature would be missing given that CSS3 supports repeating-linear-gradient
and repeating-radial-gradient
background styles.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With