Making the gradient line match a desired shape
<!DOCTYPE HTML> <html> <head> <title>Example</title> <style> canvas {border: thin solid black; margin: 4px} </style> </head> <body> <canvas id="canvas" width="500" height="140"> Your browser doesn't support the <code>canvas</code> element </canvas> <script> let ctx = document.getElementById("canvas").getContext("2d"); let grad = ctx.createLinearGradient(10, 10, 60, 60); grad.addColorStop(0, "red"); grad.addColorStop(0.5, "white"); grad.addColorStop(1, "black"); /* w w w . j a v a 2s. com*/ ctx.fillStyle = grad; ctx.fillRect(0, 0, 500, 140); </script> </body> </html>
The following code matches the rectangle to the gradient.
<!DOCTYPE HTML> <html> <head> <title>Example</title> <style> canvas {border: thin solid black; margin: 4px} </style> </head> <body> <canvas id="canvas" width="500" height="140"> Your browser doesn't support the <code>canvas</code> element </canvas> <script> let ctx = document.getElementById("canvas").getContext("2d"); let grad = ctx.createLinearGradient(10, 10, 60, 60); grad.addColorStop(0, "red"); grad.addColorStop(0.5, "white"); grad.addColorStop(1, "black"); //from www . j a va 2s. co m ctx.fillStyle = grad; ctx.fillRect(10, 10, 50, 50); </script> </body> </html>