用canvas绘制的折线图 +解析



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>

你可能感兴趣的:(前端学习笔记)