首先来看下线性渐变
- //第一步
- let grd = context.createLinearGradient(xstart, ystart, xend, yend);
-
- //第二步
- Grd.addColorStop(stop, color);
程序运行截图如下:
源码如下:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Title</title>
- </head>
- <body>
-
- <canvas id="canvas" style="border: 1px solid #aaa; display: block; margin: 50px auto;">
- 当前浏览器不支持canvas
- </canvas>
-
- <script>
-
- window.onload = function(){
-
- let canvas = document.getElementById("canvas");
- canvas.width = 800;
- canvas.height = 800;
- let context = canvas.getContext("https://cdn.jxasp.com:9143/image/2d");
-
- context.save();
- let line1 = context.createLinearGradient(0, 0, 400, 800);
- line1.addColorStop(0.0, "#fff");
- line1.addColorStop(1.0, "#000");
- context.fillStyle = line1;
- context.fillRect(0, 0, 400, 800);
- context.restore();
-
- context.save();
- let line2 = context.createLinearGradient(400, 0, 400, 800);
- line2.addColorStop(0.0, "red");
- line2.addColorStop(0.5, "blue");
- line2.addColorStop(1.0, "green");
- context.fillStyle = line2;
- context.fillRect(400, 0, 400, 800);
- context.restore();
- }
-
- </script>
-
- </body>
- </html>
下面是非线性变换
- let grd = context.createRadialGradient(x0, y0, r0, x1, y1, r1);
- grd.addColorStop(stop, color);
程序运行截图如下:
代码如下:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Title</title>
- </head>
- <body>
-
- <canvas id="canvas" style="border: 1px solid #aaa; display: block; margin: 50px auto;">
- 当前浏览器不支持canvas
- </canvas>
-
- <script>
-
- window.onload = function(){
-
- let canvas = document.getElementById("canvas");
- canvas.width = 800;
- canvas.height = 800;
- let context = canvas.getContext("https://cdn.jxasp.com:9143/image/2d");
-
- let radialGrad = context.createRadialGradient(400, 400, 0, 400, 400, 500);
- radialGrad.addColorStop(0.0, "white");
- radialGrad.addColorStop(0.25, "yellow");
- radialGrad.addColorStop(0.5, "green");
- radialGrad.addColorStop(0.75, "blue");
- radialGrad.addColorStop(1.0, "black");
- context.fillStyle = radialGrad;
- context.fillRect(0, 0, 800, 800);
- }
-
- </script>
-
- </body>
- </html>