laxexue 2019-06-27
参考了 https://www.cnblogs.com/yxysu...
这里只是给自己简单的记录下代码
发现很多变量不知道咋称呼它 - -
意会意会
<canvas canvas-id="chart" class="mychart" style="width: 600rpx;height: 600rpx"></canvas>
全局定义一个
const cx = wepy.createCanvasContext('chart')
drawChart() { // 轴 let grades = [7,8,6,10,8,5,7,30,1,8,5,7,5,1,8,12,52,12,49,30,12] //数据源 let max = Math.max.apply(null,grades); let min = Math.min.apply(null,grades); this.Ydiff = max-min let xW = this.Xwidth / grades.length this.$apply() let kedu = Math.round((max-min) / 10) // 10是y轴的刻度数量 this.drawLine(0,0,300,0,0.5,'#999999') this.drawLine(0,200,0,-80,0.5,'#999999') // 刻度线 for(let i=kedu; i<=max; i=i+kedu){ cx.fillText(i,this.x(-15),this.y(this.gg(i))+10) this.drawLine(0,this.gg(i),250,this.gg(i),0.5,'#eee') } let color = [] for (let i in grades ) { color[i] = this.getRandomColor() } for(let i=xW,j=0;j<color.length;j++,i=i+xW){ this.drawLine(i,1,i,this.gg(grades[j]),8,color[j]); } cx.draw() }
x(x) { return x + 20 } y(y) { return 300-y } g(grade) { return 15 * grade; } gg(grade) { return 200 / this.Ydiff * grade } drawLine(b_x, b_y, e_x, e_y, width, color) { cx.strokeStyle = color cx.lineWidth = width cx.beginPath() cx.moveTo(this.x(b_x), this.y(b_y)) cx.lineTo(this.x(e_x), this.y(e_y)) cx.closePath() cx.stroke() } getRandomColor() { let color = '#' let alArr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f'], for (let i = 0; i < 6; i++) { color += alArr[Math.floor(Math.random() * (16))] } return(color) }