首先绘制一块画布
<canvas width="600px" height="400px"></canvas>
在body中给画布设置样式
<style>
canvas{
border: 1px solid black;
margin: 100px 500px;
}
</style>
然后在scrlpt标签中获取画布的对象和工具:
var maycanvas=document.querySelector("canvas"); var ctx=maycanvas.getContext("2d");
随机获取画布的宽高
var canvasW=ctx.canvas.width var canvasH=ctx.canvas.height
将每个每个点的坐标用数组装起来
var arr=[{x:50,y:100},{x:100,y:120}, {x:200,y:120},{x:300,y:280},{x:450,y:200}]
自定义一个随机变量,用于绘制网格
var unm=10;
利用循环绘制网格
for(i=1;i<=60;i++){ ctx.moveTo(0,unm*i) ctx.lineTo(canvasW,unm*i) ctx.strokeStyle="#eee" ctx.stroke() ctx.moveTo(unm*i,0) ctx.lineTo(unm*i,canvasH) ctx.strokeStyle="#eee" ctx.stroke() }
绘制x轴和箭头:
ctx.beginPath() ctx.moveTo(2*unm,canvasH-2*unm) ctx.lineTo(canvasW-4*unm,canvasH-2*unm) ctx.strokeStyle="black" ctx.stroke() ctx.beginPath() var bian=7 ctx.moveTo(canvasW-4*unm,canvasH-2*unm) ctx.lineTo(canvasW-4*unm-2*bian,canvasH-2*unm+bian) ctx.lineTo(canvasW-4*unm-2*bian,canvasH-2*unm-bian) ctx.lineTo(canvasW-4*unm,canvasH-2*unm) ctx.strokeStyle="black" ctx.fill() ctx.stroke()
绘制y轴和箭头:
ctx.beginPath() ctx.moveTo(2*unm,canvasH-2*unm) ctx.lineTo(2*unm,2*unm) ctx.strokeStyle="black" ctx.stroke() ctx.moveTo(2*unm,2*unm) ctx.lineTo(2*unm-bian,2*unm+2*bian) ctx.lineTo(2*unm+bian,2*unm+2*bian) ctx.lineTo(2*unm,2*unm) ctx.strokeStyle="black" ctx.fill() ctx.stroke()
绘制折现
ctx.beginPath() ctx.moveTo(2*unm,canvasH-2*unm) for(i=0;i<arr.length;i++){ ctx.lineTo(2*unm+arr[i].x,canvasH-2*unm-arr[i].y) ctx.fillText("("+arr[i].x+","+arr[i].y+")",2*unm+arr[i].x+10,canvasH-2*unm-arr[i].y) } ctx.strokeStyle="red" ctx.stroke()
绘制每个人点的正方形:
ctx.beginPath() for(j=0;j<arr.length;j++){ ctx.fillStyle="red" ctx.fillRect(2*unm+arr[j].x-5,canvasH-2*unm-arr[j].y-5,10,10) ctx.fill() }
效果图: