<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>坐标点进行连线</title>
<style>
canvas{
border: 1px solid red;
}
</style>
</head>
<body>
<canvas></canvas>
</body>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var padding = 30;
var arrowHeight = 20,
arrowWidth = 10;
var x0 = padding,
y0 = canvas.height - padding;
var maxX = canvas.width - padding*2 -arrowHeight,
maxY = canvas.height - padding*2 - arrowHeight;
//绘制坐标轴
//X轴
ctx.moveTo(x0,y0);
ctx.lineTo(x0,y0 - maxY-arrowHeight);
//Y轴
ctx.moveTo(x0,y0);
ctx.lineTo(x0 + maxX +arrowHeight,y0);
ctx.stroke();
//绘制箭头
//X轴
ctx.beginPath();
ctx.moveTo(x0+maxX+arrowHeight,y0);
ctx.lineTo(x0+maxX,y0-arrowWidth*0.5);
ctx.lineTo(x0+maxX+arrowHeight*0.5,y0);
ctx.lineTo(x0+maxX,y0+arrowWidth*0.5);
//Y轴
ctx.moveTo(x0,y0-maxY-arrowHeight);
ctx.lineTo(x0-arrowWidth*0.5,y0-maxY);
ctx.lineTo(x0,y0-maxY-arrowHeight*0.5);
ctx.lineTo(x0+arrowWidth*0.5,y0-maxY);
ctx.fill();
//绘制点
ctx.beginPath();
var data = [ [ 10, 20 ], [ 15, 13 ], [ 17, 30 ], [ 30, 10 ], [ 20, 15 ] ];
//取点的数据
/*将其中X与Y的最大值找出来,因为要做一个比例的转化:
点坐标/max点坐标 = 页面上点坐标/canvas的轴的最大值*/
var pointX = Math.max.apply(null,data.map(function(v){return v[0];}));
var pointY = Math.max.apply(null,data.map(function(v){return v[1];}));
//使用冒泡排序
for(var i =0;i<data.length-1;i++){
for(var j =0;j<data.length-1-i;j++){
if(data[j][0]>data[j+1][0]){
var temp = data[j +1];
data[j+1] = data[j];
data[j] = temp;
}
}
}
//声明一个新数组用于存储数据
var arr = [];
for(var i = 0 ; i < data.length ; i++){
var tempX = data[i][0]/pointX*maxX,
tempY = data[i][1]/pointY*maxY;
//一定要记得坐标的最后一步转换
var X = x0 + tempX,
Y = y0 - tempY;
arr.push([X,Y]);
ctx.moveTo(X-4,Y-4);
ctx.lineTo(X-4,Y+4);
ctx.lineTo(X+4,Y+4);
ctx.lineTo(X+4,Y-4);
}
console.log(arr);
ctx.fill();
//画线
ctx.beginPath();
//比较值,优化直线
arr.forEach(function(v,i){
ctx[['moveTo','lineTo'][i>0?1:0]](v[0],v[1]);
})
/*for(var i = 0 ; i < data.length-1 ; i++){
var tempX = data[i][0]/pointX*maxX,
tempY = data[i][1]/pointY*maxY;
var tempX1 = data[i+1][0]/pointX*maxX,
tempY1 = data[i+1][1]/pointY*maxY;
//一定要记得坐标的最后一步转换
var X = x0 + tempX,
Y = y0 - tempY,
X1 = x0 + tempX1,
Y1 = y0 - tempY1;
ctx.moveTo(X,Y);
ctx.lineTo(X1,Y1);
}*/
ctx.stroke();
</script>
</html>