<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
    <canvas id="ca" width="300" height="300"></canvas>
  <br>随机绘制折线图按钮:
<button id="btn">重新绘制</button> <script> var uriage = [80, 92, 104, 110, 68, 50, 45, 90, 74, 68, 98, 103]; window.onload = function(){ drawChart(shuffle(uriage)); } _$('btn').addEventListener('click', function(){ drawChart(shuffle(uriage)); }, false); function drawChart(data){ var a_canvas = _$('ca'); var ctx = a_canvas.getContext('2d'); var gradient = ctx.createLinearGradient(0, 0, 0, 300); gradient.addColorStop(0, '#e0e0e0'); gradient.addColorStop(1, '#ffffff'); ctx.fillStyle = gradient; ctx.fillRect(0, 0, a_canvas.width, a_canvas.height); var grid_cols = data.length + 1; var grid_rows = 4; var cell_width = a_canvas.width / grid_cols; var cell_height = a_canvas.height / grid_rows; ctx.beginPath(); for(var row = 0; row <= grid_rows; row++){ var y = row * cell_height; ctx.moveTo(0, y); ctx.lineTo(a_canvas.width, y); } for(var col = 0; col <= grid_cols; col++){ var x = col * cell_width; ctx.moveTo(x, 0); ctx.lineTo(x, a_canvas.height); } ctx.lineWidth = 1; ctx.strokeStyle = '#c0c0c0'; ctx.stroke(); var max_v = 0; for(var i = 0; i < data.length; i++){ if(data[i] > max_v) max_v = data[i]; } max_v = max_v * 1.1; var points = []; for(var i = 0; i < data.length; i++){ var v = data[i]; var px = cell_width * (i + 1); var py = a_canvas.height - a_canvas.height * (v / max_v); points.push({ 'x': px, 'y': py }); } for(var i = 0; i < points.length; i++){ ctx.beginPath(); ctx.arc(points[i]['x'], points[i]['y'], 2, 0, 2*Math.PI); ctx.fillStyle = '#00ff00' ctx.fill(); } ctx.beginPath(); ctx.moveTo(points[0]['x'], points[0]['y']); for(var i = 0; i < points.length; i++){ ctx.lineTo(points[i]['x'], points[i]['y']); ctx.lineWidth = 2; ctx.strokeStyle = '#ee0000'; ctx.stroke(); } } function shuffle(arr){ if(Object.prototype.toString.call(arr) !== '[object Array]') return; var len = arr.length - 1, index = null; while(len > 0){ index = Math.floor(len * Math.random()); arr[len] = [ arr[index], arr[index]=arr[len] ][0]; len--; } return arr; } function _$(anchor){ if(typeof anchor !== 'string') return; return document.getElementById(anchor); } </script> </body> </html>

 

posted on 2015-09-17 08:49  -大灰羊-  阅读(342)  评论(0编辑  收藏  举报