运行效果截图如下:
具体代码如下:
<!DOCTYPE html> <html> <head> <title>demo</title> <style type="text/css"> #canvas { border:3px solid gray; } </style> </head> <body> <canvas></canvas> </body> <script type="text/javascript"> var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); ctx.beginPath(); ctx.rect(0, 0, 200, 200); ctx.closePath(); var gradient = ctx.createLinearGradient(0, 0, 200, 200); gradient.addColorStop(0, "gray"); gradient.addColorStop(0.5, "red"); gradient.addColorStop(1, "blue"); ctx.fillStyle = gradient; ctx.fill(); </script> </html>