index.html:
<!DOCTYPE HTML>
<html>
<style type="text/css">
#myCanvas {border: 1px solid #BEBEBE;}
</style>
<body>
<canvas id="myCanvas" width="800" height="600">你的浏览器不支持 HTML5</canvas>
<script src="index.js"></script>
</body>
</html>
Javascript:
(function(){ // 闭包,防止变量、方法重复 var canvasDom = document.getElementById("myCanvas"); var context = canvasDom.getContext("2d"); // 获取绘制功能的对象(context:上下文) drawradientLine(10, 10, 10+500, 10, 50, ['red', 'yellow', 'green', 'orange', '#FF00FF']); /** * [drawradientLine 画颜色线性变化的线条] * @param {[type]} x1 [起点x坐标] * @param {[type]} y1 [起点y坐标] * @param {[type]} x2 [终点x坐标] * @param {[type]} y2 [终点y坐标] * @param {[type]} lineWidth [线条宽度] * @param {[type]} colors [颜色数组,均匀分布的] * @return {[type]} [无] */ function drawradientLine(x1, y1, x2, y2, lineWidth, colors) { context.beginPath(); // 开始路径,如果没有这个和结束路径包围,所有线条都是最后那根线条的样式了 context.moveTo(x1, y1); // 开始位置 context.lineTo(x2, y2); // 画到此处 context.lineWidth = lineWidth; var grd = context.createLinearGradient(x1, y1, x2, y2); //线性渐变的起止坐标 for (var i=0; i<colors.length; i++) { grd.addColorStop(i / colors.length, colors[i]); } context.strokeStyle = grd; context.closePath(); // 结束路径,应与开始路径呼应(会不会导致内存泄露跟实现有关系) context.stroke(); } })();