Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a repeating CanvasGradient

Tags:

html5-canvas

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.

like image 727
Andy Avatar asked Sep 11 '25 03:09

Andy


1 Answers

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.

like image 67
Andy Avatar answered Sep 14 '25 08:09

Andy