1、线性渐变:

  1. <style>
  2. canvas {
  3. width: 500px;
  4. height: 300px;
  5. border: 1px solid;
  6. }
  7. </style>
  8. </head>
  9. <body>
  10. <canvas id="can" width="500px" height="300px"></canvas>
  11. <script>
  12. var canvas = document.getElementById("can");
  13. var ctx = canvas.getContext("2d");
  14. ctx.beginPath();
  15. //线性渐变的起始点是坐标系的原点,而不是矩形的原点
  16. var bg = ctx.createLinearGradient(0,0,200,0);//线性渐变,设两个点
  17. bg.addColorStop(0,"white");//只有0~1
  18. bg.addColorStop(0.5,"blue");
  19. bg.addColorStop(1,"black");
  20. ctx.fillStyle = bg;
  21. ctx.fillRect(0,0,200,100);
  22. </script>
  23. </body>