How to create gradients in HTML5 canvas? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to create gradients in HTML5 canvas?

If you want to create gradients, use this code! var c=document.getElementById("canvas1"); var ctx=c.getContext("2d"); var grd=ctx.createRadialGradient(75,50,5,90,60,100); grd.addColorStop(0,"red"); grd.addColorStop(1,"white"); // Fill with gradient ctx.fillStyle=grd; ctx.fillRect(10,10,150,100); For example: https://code.sololearn.com/WhqgNnn3ipYr/?ref=app

19th Jul 2018, 7:03 AM
Orsrozsondai
Orsrozsondai - avatar
2 Answers
+ 1
https://www.sololearn.com/discuss/1316935/?ref=app
21st Jul 2018, 12:47 AM
Lemuel
Lemuel - avatar
0
Defining a gradient (left to right) that goes from black to white, as the fill style for the rectangle: var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); var grd=ctx.createLinearGradient(0,0,170,0); grd.addColorStop(0,"black"); grd.addColorStop(1,"white"); ctx.fillStyle=grd; ctx.fillRect(20,20,150,100); For detail and more examples: https://www.w3schools.com/tags/canvas_createlineargradient.asp
22nd Jul 2018, 1:19 PM
kp kalia
kp kalia - avatar