Skip to content Skip to sidebar Skip to footer

How To Make A Repeating Canvasgradient

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 an

Solution 1:

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 = 10var 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.

Post a Comment for "How To Make A Repeating Canvasgradient"