用canvas繪製的折線圖 +解析
阿新 • • 發佈:2019-02-05
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>$Title$</title> </head> <body> <canvas id="canvas" width="800" height="600" style="border:1px solid red"></canvas> </body> <script> var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var yTopX = 50, yTopY = 50, yLength = 500, xLength = 500, b = 30, h = 30; var zeroX=yTopX,zeroY=yTopY+yLength; //1、繪製y軸小三角形 ctx.moveTo(yTopX-b/2,yTopY+h);//p1 ctx.lineTo(yTopX,yTopY); ctx.lineTo(yTopX+b/2,yTopY+h);//p2 //2、繪製y軸、x軸折線 ctx.moveTo(yTopX,yTopY); ctx.lineTo(zeroX,zeroY); ctx.lineTo(yTopX+xLength,yTopY+yLength); //3、繪製x軸小三角形(r1-r2-r3) ctx.moveTo(yTopX+xLength-h,yTopY+yLength-b/2); ctx.lineTo(yTopX+xLength,yTopY+yLength); ctx.lineTo(yTopX+xLength-h,yTopY+yLength+b/2); ctx.stroke(); var data=[{x:50,y:250},{x:160,y:170},{x:200,y:200},{x:280,y:155},{x:350,y:300}]; //data2儲存了每一個數據位於畫布中的座標var data2=data.map(function(obj){ var objNew={}; objNew.x=zeroX+obj.x; objNew.y=zeroY-obj.y; return objNew; }); console.log(data2); //繪製每一個點 data2.forEach(function(obj){ //以obj為中心,繪製邊長為4的實心小正方形 var x=obj.x,y=obj.y; ctx.beginPath(); ctx.moveTo(x-2,y-2); ctx.lineTo(x+2,y-2); ctx.lineTo(x+2,y+2); ctx.lineTo(x-2,y+2); ctx.fill(); }); //連線 ctx.beginPath(); ctx.moveTo(zeroX,zeroY); data2.forEach(function(obj){ ctx.lineTo(obj.x,obj.y); }); ctx.stroke(); </script> </html>