canvas畫水平曲線走勢圖
阿新 • • 發佈:2019-02-05
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta charset="utf-8"> <meta name="renderer" content="webkit"> <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1"> <title> </title> <style type="text/css"> </style> <script type="text/javascript"> var drawLine = {}; !function () { //求陣列最大值 Array.prototype.max = function () { var max = this[0]; var len = this.length; for (var i = 1; i < len; i++) { if (this[i] > max) { max = this[i]; } } return max; } function draw(arr) { var width = 250, height = 100; var maxV = arr.max(); //計算y軸增量 var yStep = height / maxV; console.log(maxV); var domCan = document.getElementById("canDom"); var g = domCan.getContext("2d"); //g.rotate(180 * Math.PI / 180);//旋轉90度 //g.translate(50, 0); //g.scale(1,-1); g.beginPath(); g.lineWidth = 2; g.strokeStyle = "#c30000"; //g.moveTo(0, 0);//開始畫圖的位置 var x_space = width / (arr.length - 1);//水平點的間隙畫素 //g.lineTo(15, 60); x,y,x表示水平向右延伸,y表示垂直高度位置,從畫板最左上角(0,0)開始計算座標 var xLen = 0; for (var i = 0; i < arr.length; i++) { var yValue = arr[i];//縱座標值 xLen += x_space; var yPont = height - yValue * yStep; if (i == 0) { xLen = 0; } var m = xLen + "," + yPont; console.log(m); g.lineTo(xLen, yPont); } //g.lineTo(15, 60); //g.lineTo(20, 30); //g.lineTo(30, 40); //g.lineTo(40, 50); g.stroke(); g.closePath(); } drawLine.minCurve = draw; //window.drawMinLine = draw; }(); window.onload = function () { var arr = [10, 50, 30, 70, 80, 40, 90, 110, 80, 60, 69, 80, 80, 10, 50, 30, 70, 80, 40, 97, 80, 70, 60, 50, 80]; //var arr = [30, 80,50,70]; //drawMinLine(arr); drawLine.minCurve(arr); } </script> </head> <body> <canvas id="canDom" width="250" height="100" style="border:1px solid #ccc;"></canvas> </body> </html>
效果圖: