AI智能
改变未来

H5、jQuery绘制折线


H5、jQuery绘制折线

html文件:

<!DOCTYPE html><html><head><meta charset=\"utf-8\"><meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"><title></title><link rel=\"stylesheet\" href=\"\"><script type=\"text/javascript\" src=\"jquery-3.3.1.min.js\"></script><script type=\"text/javascript\" src=\"chapter5_1.js\"></script><script type=\"text/javascript\" src=\"chapter5.js\"></script><style type=\"text/css\" media=\"screen\">#canvas{border:1px solid red;margin:100px;}</style></head><body><canvas id=\"canvas\" width=\"700\" height=\"600\"></canvas></body></html>

js文件:

//插件function chapter5(options,obj){var cas = obj[0].getContext(\'2d\');//画笔//画竖线var w = obj.width(),h = obj.height(),len_x = options.x.length,len_y = options.y.length,//横向小段stepX = (w-100)/(len_x-1),stepY = (h-100)/(len_y-1);//坐标//竖线var py1 = [50,50],py2 = [50,h-50];//titlecas.font = \"20px 微软雅黑\";cas.fillText(options.tittle,3,20);//画坐标for (var i = 0 ; i <len_x; i++){var str = options.x[i];cas.font = \"20px 微软雅黑\";//填文字cas.fillText(str,py1[0]-15,py2[1]+25);cas.beginPath();//画线cas.moveTo(py1[0],py1[1]);cas.lineTo(py2[0],py2[1]);cas.stroke();py1[0] += stepX;py2[0] += stepX;}//横线var py3 = [50,50],py4=[w-50,50];for (var i = 0 ;i < len_y; i++){//var str = options.y[i];var str = options.y[len_y-i-1];cas.font = \"20px 微软雅黑\";//cas.fillText();//cas.fillText(str,3,py4[1]+5);cas.fillText(str,3,py4[1]+5);cas.beginPath();cas.moveTo(py3[0],py3[1]);cas.lineTo(py4[0],py4[1]);cas.stroke();py3[1] += stepY;py4[1] += stepY;}//绘制折线var py5 = [50,50];py6 = [50,h-50];//平均分成10份,每份占40for(var i = 0 ; i <len_x ; i++){//蓝色折线var data =options.data;var len = data.length;for(var j =0;j<len;j++){// var data = options.data;var y1=(h-100)*data[j].data1.data_num[i]/options.y[len_y-1];var y2=(h-100)*data[j].data1.data_num[i+1]/options.y[len_y-1];cas.beginPath();cas.strokeStyle= data[j].data1.color;// cas.strokeStyle = data[0].data1.color;cas.moveTo(py5[0],h-50-y1);cas.lineTo(py5[0]+stepX,h-50-y2)cas.stroke();cas.beginPath();//白色填充可以使线条被覆盖cas.fillStyle =\"#fff\";cas.arc(py5[0],h-50-y1,5,0,Math.PI*2,true);cas.fill();cas.stroke();}py5[0]+=stepX;//累加//红色色折线}}

json处理数据:

//调用插件//json数据$(function(){options ={x:[\"10月\",\"11月\",\"12月\",\"1月\",\"2月\",\"3月\"],//刻度y:[0,50,100,150,200,250,300],tittle:\"万元/m2\",data:[{data1:{\"color\":\"blue\",data_num:[60,200,150,130,240,290]}},{data1:{\"color\":\"red\",data_num:[110,40,15,70,160,280]}}],};obj = $(\"#canvas\");new chapter5(options,obj);});

结果:

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » H5、jQuery绘制折线