Generating and Using Radial Gradients to Fill Shapes
<!DOCTYPE html> <html> <head> <title>Canvas Demo</title> <style> canvas { //from ww w.java 2 s . c o m border: 1px solid #000; } </style> </head> <body> <canvas id="myCanvas" width="200" height="200">Did You Know: Every time you use a browser that doesn't support HTML5 </canvas> <script> // Get the context we will be using for drawing. let myCanvas = document.getElementById('myCanvas'); let myContext = myCanvas.getContext('2d'); /** * Draws a circle of the specified dimensions at the target coordinates and * fills it with the current fill style. * @param {number} x The x coordinate of the center of the circle. * @param {number} y The y coordinate of the center of the circle. * @param {number} radius The radius of the circle. */ function fillCircle(x, y, radius) { myContext.beginPath(); myContext.arc(x, y, radius, 0, 6.3); myContext.fill(); myContext.closePath(); } /** * Returns a random integer between the specified minimum and maximum values. * @param {number} min The lower boundary for the random number. * @param {number} max The upper boundary for the random number. * @return {number} */ function getRandomIntegerBetween(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } /** * Returns a random color formatted as an rgb string. * @return {string} */ function getRandRGB() { let randRed = getRandomIntegerBetween(0, 255); let randGreen = getRandomIntegerBetween(0, 255); let randBlue = getRandomIntegerBetween(0, 255); return 'rgb(' + randRed + ', ' + randGreen + ', ' + randBlue + ')'; } let cycles = 10, i = 0; for (i = 0; i < cycles; i++) { let randX = getRandomIntegerBetween(50, 150); let randY = getRandomIntegerBetween(50, 150); let randRadius = getRandomIntegerBetween(10, 50); let randGrad = myContext.createRadialGradient(randX, randY, 0, randX, randY, randRadius); let randColor1 = getRandRGB(); let randColor2 = getRandRGB(); randGrad.addColorStop(0, randColor1); randGrad.addColorStop(1, randColor2); myContext.fillStyle = randGrad; fillCircle(randX, randY, randRadius); } </script> </body> </html>