初始接口
<body> <canvas id=“canvas”></canvas> <script> var canvas = document.getElementById(“canvas”); var context = canvas.getContext(“2d”); //使用content进行绘制 </script> </body>
直线绘制
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <canvas id="canvas" style="border: 1px solid #ddd; margin: 0 auto"></canvas> <script> window.onload = function () { var canvas = document.getElementById("canvas"); canvas.width = 1024; canvas.height = 768; //绘制的接口 var context = canvas.getContext("2d"); //Draw a line //意图绘制,状态绘制 //路径定义的首尾 context.beginPath(); context.moveTo(100, 100);//笔尖 context.lineTo(700, 700);//笔尾 context.lineTo(100, 700); context.lineTo(100, 100); context.closePath(); // context.fillStyle = "rgb(2,100,30)"; // //填充颜色 // context.fill(); //线条的宽度 context.lineWidth = 5; //线条的样式 context.strokeStyle = "#058"; //具体绘制 //笔画 context.stroke(); context.beginPath(); context.moveTo(200, 100); context.lineTo(700, 600); context.closePath(); context.strokeStyle = "black"; context.stroke(); //canvas是基于状态绘制的 } </script> </body> </html>
方法
context.beginPath();
context.moveTo();
context.lineTo();
context.closePath();
context.fill();
context.stroke();
属性
context.fillStyle;
context.strokeStyle
context.lineWidth