Canavs初学


<
canvas id="canvas" style="border:1px solid #f00;"></canvas>

公用js:

var canvas = document.getElementById("canvas");
canvas.width = 600;
canvas.height = 600;//此处也可直接在标签中添加width height属性
var context = canvas.getContext("2d");

绘制直线:

context.moveTo(100,100);//状态
context.lineTo(200,200);//状态  直线
context.lineWidth = 6;
context.strokeStyle = "#00f";
context.stroke();//绘制边框

效果如图:

绘制三角形(空心):

context.moveTo(100,100);//状态  起点
context.lineTo(200,200);//状态  直线
context.lineTo(100,200);
context.lineTo(100,100);//直角三角形

context.lineWidth = 6;//边框宽度
context.strokeStyle = "#00f";//边框颜色
context.stroke();//绘制边框

效果如图:

从效果图中可以看出最后的点并没有完全闭合,此处可使用lineCap属性,在上面代码中加上

context.lineCap="round";//butt,round,square

效果如下:

只有最后一点是圆形,而另外两个角处是非圆形(???????)

绘制三角形(实心):

context.moveTo(100,100);//状态  起点
context.lineTo(200,200);//状态  直线
context.lineTo(100,200);
context.lineTo(100,100);//直角三角形

context.lineWidth = 6;
context.lineCap = "round";
context.strokeStyle = "#00f";
context.stroke();//绘制边框(边框不能完全闭合??????)

context.fillStyle="rgb(255,0,0)";
context.fill();//填充背景色

效果如图:

在三角形(实心)基础上绘制另一条直线:

context.moveTo(100,100);//状态  起点
context.lineTo(200,200);//状态  直线
context.lineTo(100,200);
context.lineTo(100,100);//直角三角形

context.lineWidth = 6;
context.lineCap = "round";
context.strokeStyle = "#00f";
context.stroke();//绘制边框(边框不能完全闭合??????)

context.fillStyle="rgb(255,0,0)";
context.fill();//填充背景色
//绘制另一条直线
context.moveTo(200,100);
context.lineTo(300,200);
context.strokeStyle="#0f0";
context.lineWidth = 2;//此处宽度比上面宽度小,因此三角形边框最内侧会被新边框覆盖
context.stroke();

效果如图:注意三角形边框(设置宽度不同)

若将第二个的lineWidth 也设置为6,效果如下图:

//绘制另一条直线
context.moveTo(200,100);
context.lineTo(300,200);
context.strokeStyle="#0f0";
context.lineWidth = 6;//此处宽度:2时比上面宽度小,因此三角形边框最内侧会被新边框覆盖
context.stroke();

context.fillStyle="#00f";
context.fill();

三角形边框宽度明显不为6(???????)

绘制不同路径使用beginPath及closePath:

context.beginPath();//开启
context.moveTo(100,100);//状态  起点
context.lineTo(200,200);//状态  直线
context.lineTo(100,200);
context.lineTo(100,100);//直角三角形
context.closePath();//关闭

context.lineWidth = 6;
context.lineCap = "round";
context.strokeStyle = "#00f";
context.stroke();//绘制边框(边框不能完全闭合??????)

context.fillStyle="rgb(255,0,0)";
context.fill();//填充背景色
//绘制另一条直线
context.beginPath();//开启
context.moveTo(200,100);
context.lineTo(300,200);
context.closePath();//关闭

context.strokeStyle="#0f0";
context.lineWidth = 6;//此处宽度:2时比上面宽度小,因此三角形边框最内侧会被新边框覆盖
context.stroke();

context.fillStyle="#00f";
context.fill();
原文地址:https://www.cnblogs.com/loveamyforever/p/8157435.html