每次lineTo后如果没有moveTo,那么下次lineTo的开始点为前一次lineTo的结束点
function draw8(id) { var canvas = document.getElementById(id); if (canvas == null) return false; var context = canvas.getContext("2d"); //context.beginPath(); context.strokeStyle = "rgb(250,0,0)"; context.fillStyle = "rgb(250,0,0)" //实验证明第一次lineTo的时候和moveTo功能一样 context.lineTo(100, 100); //之后的lineTo会以上次lineTo的节点为开始 context.lineTo(200, 200); context.lineTo(200, 100); context.moveTo(200, 50); context.lineTo(100,50); context.stroke(); }下面给出书本的例子,一朵绿色的菊花,涉及数学,不多解析,有兴趣的自己研究
function draw1(id) { var canvas = document.getElementById(id); if (canvas == null) return false; var context = canvas.getContext("2d"); context.fillStyle = "#EEEEFF"; context.fillRect(0, 0, 400, 300); var n = 0; var dx = 150; var dy = 150; var s = 100; context.beginPath(); context.fillStyle = 'rgb(100,255,100)'; context.strokeStyle = 'rgb(0,0,100)'; var x = Math.sin(0); var y = Math.cos(0); var dig = Math.PI / 15 * 11; for (var i = 0; i < 30; i++) { var x = Math.sin(i * dig); var y = Math.cos(i * dig); context.lineTo(dx + x * s, dy + y * s); } context.closePath(); context.fill(); context.stroke(); } 绘制贝塞尔曲线(贝济埃、bezier) context.bezierCurveTo(cp1x,cp1y,cp2x,cp2y,x,y)
绘制二次样条曲线 context.quadraticCurveTo(qcpx,qcpy,qx,qy)
cp1x:第一个控制点x坐标
cp1y:第一个控制点y坐标
cp2x:第二个控制点x坐标
cp2y:第二个控制点y坐标
x:终点x坐标
y:终点y坐标
qcpx:二次样条曲线控制点x坐标
qcpy:二次样条曲线控制点y坐标
qx:二次样条曲线终点x坐标
qy:二次样条曲线终点y坐标
function draw24(id) { var canvas = document.getElementById(id); if (canvas == null) { return false; } var context = canvas.getContext("2d"); context.moveTo(50, 50); context.bezierCurveTo(50, 50,150, 50, 150, 150); context.stroke(); context.quadraticCurveTo(150, 250, 250, 250); context.stroke(); }下面给出书本的例子,一朵扭曲的绿色菊花...编书这哥们对菊花情有独钟啊--
function draw2(id) { var canvas = document.getElementById(id); if (canvas == null) { return false; } var context = canvas.getContext("2d"); context.fillStyle = "#EEEFF"; context.fillRect(0, 0, 400, 300); var n = 0; var dx = 150; var dy = 150; var s = 100; context.beginPath(); context.globalCompositeOperation = 'and'; context.fillStyle = 'rgb(100,255,100)'; var x = Math.sin(0); var y = Math.cos(0); var dig = Math.PI / 15 * 11; context.moveTo(dx, dy); for (var i = 0; i < 30; i++) { var x = Math.sin(i * dig); var y = Math.cos(i * dig); context.bezierCurveTo(dx + x * s, dy + y * s - 100, dx + x * s + 100, dy + y * s, dx + x * s, dy + y * s); } context.closePath(); context.fill(); context.stroke(); } 线性渐变var lg= context.createLinearGradient(xStart,yStart,xEnd,yEnd)
线性渐变颜色lg.addColorStop(offset,color)
xstart:渐变开始点x坐标
ystart:渐变开始点y坐标
xEnd:渐变结束点x坐标
yEnd:渐变结束点y坐标
offset:设定的颜色离渐变结束点的偏移量(0~1)
color:绘制时要使用的颜色
给出书本偏移量的解析图,从图可以看出线性渐变可以是两种以上颜色的渐变