使用canvas仿Echarts实现金字塔图的实例代码
前言
最近公司项目都偏向于数字化大屏展示????,而这次发给我的项目原型中出现了一个金字塔图????️, 好巧不巧,由于我们的图表都是使用echarts,而echarts中又不支持金字塔图,作为一个喜欢造*的前端开发,虽然自身技术不咋滴,但喜欢攻克难题的精神还是有的????, 不断地内卷,才是我们这些普通前端开发的核心竞争力????,所以就有了仿echarts实现金字塔图的想法。
不多说先上效果
项目地址:(https://github.com/shdjason/pyramid.git)
正文
项目实现可传入配置有:主体图位置(distance)、主体图偏移度(offset)、数据排序(sort)、图颜色(color)、数据文本回调(fontformatter)、tooltip配置(tooltip)、数据展示样式配置(infostyle)等
初始化canvas基本信息 并实现大小自适应
<template> <div id="canvas-warpper"> <div id="canvas-tooltip"></div> </div> </template>
先创建 canvas画布
// 创建canvas元素 this.canvas = document.createelement('canvas') // 把canvas元素节点添加在el元素下 el.appendchild(this.canvas) this.canvaswidth = el.offsetwidth this.canvasheight = el.offsetheight // 将canvas元素设置与父元素同宽 this.canvas.setattribute('width', this.canvaswidth) // 将canvas元素设置与父元素同高 this.canvas.setattribute('height', this.canvasheight)
获取画布中心点 方便后面做自适应和定点
this.canvascenter = [ math.round((this.canvaswidth - this.integration.distance[0] * 2) / 2) + this.integration.distance[0], math.round((this.canvasheight - this.integration.distance[1] * 2) / 2) + this.integration.distance[1] ]
监听传来的数据 并计算数据占比
刚好在这编写 数据排序(sort)的传入配置
watch: { data: { immediate: true, deep: true, handler(newvalue) { // 数据总量 let totaldata = 0 newvalue.foreach(element => { totaldata = totaldata + number(element.value) }) this.datainfo = newvalue.map(item => { const accounted = (item.value / totaldata) * 100 return { ...item, accounted, title: this.integration.title } }) if (this.integration.sort === 'max') { this.datainfo.sort((a, b) => { return a.value - b.value }) } else if (this.integration.sort === 'min') { this.datainfo.sort((a, b) => { return b.value - a.value }) } } } },
下面可以确定金字塔4个基本点的位置了
这几个基本点的位置决定在后面金字塔展示的形状 可以根据自己的审美进行微调
if (this.canvas.getcontext) { this.ctx = this.canvas.getcontext('2d') // 金字塔基本点位置 this.point.top = [this.canvascenter[0] - this.canvaswidth / 13, this.integration.distance[1]] this.point.left = [ this.integration.distance[0] * 1.5, this.canvasheight - this.integration.distance[1] - this.canvasheight / 5 ] this.point.right = [ this.canvaswidth - this.integration.distance[0] * 1.9, this.canvasheight - this.integration.distance[1] - this.canvasheight / 5 ] this.point.bottom = [ this.canvascenter[0] - this.canvaswidth / 13, this.canvasheight - this.integration.distance[1] ] this.point.shadow = [ this.integration.distance[0] - this.canvascenter[0] / 5, this.canvasheight / 1.2 - this.integration.distance[1] ] for (const key in this.point) { this.point[key][0] = this.point[key][0] + this.integration.offset[0] this.point[key][1] = this.point[key][1] + this.integration.offset[1] } } else { throw 'canvas下未找到 getcontext方法' }
完整代码
let el = document.getelementbyid('canvas-warpper') // 创建canvas元素 this.canvas = document.createelement('canvas') // 把canvas元素节点添加在el元素下 el.appendchild(this.canvas) this.canvaswidth = el.offsetwidth this.canvasheight = el.offsetheight // 将canvas元素设置与父元素同宽 this.canvas.setattribute('width', this.canvaswidth) // 将canvas元素设置与父元素同高 this.canvas.setattribute('height', this.canvasheight) this.canvascenter = [ math.round((this.canvaswidth - this.integration.distance[0] * 2) / 2) + this.integration.distance[0], math.round((this.canvasheight - this.integration.distance[1] * 2) / 2) + this.integration.distance[1] ] if (this.canvas.getcontext) { this.ctx = this.canvas.getcontext('2d') // 金字塔基本点位置 this.point.top = [this.canvascenter[0] - this.canvaswidth / 13, this.integration.distance[1]] this.point.left = [ this.integration.distance[0] * 1.5, this.canvasheight - this.integration.distance[1] - this.canvasheight / 5 ] this.point.right = [ this.canvaswidth - this.integration.distance[0] * 1.9, this.canvasheight - this.integration.distance[1] - this.canvasheight / 5 ] this.point.bottom = [ this.canvascenter[0] - this.canvaswidth / 13, this.canvasheight - this.integration.distance[1] ] this.point.shadow = [ this.integration.distance[0] - this.canvascenter[0] / 5, this.canvasheight / 1.2 - this.integration.distance[1] ] for (const key in this.point) { this.point[key][0] = this.point[key][0] + this.integration.offset[0] this.point[key][1] = this.point[key][1] + this.integration.offset[1] } } else { throw 'canvas下未找到 getcontext方法' } this.topangle.ltb = this.angle(this.point.top, this.point.left, this.point.bottom) this.topangle.rtb = this.angle(this.point.top, this.point.right, this.point.bottom) // 计算各数据点位置 this.calculationpointposition(this.datainfo) },
计算金字塔每条边的角度
为了后面给每个数据定点 但是 唉~ 奈何数学太差 所以我就想到了一个方法 :
每条数据的定点范围肯定都是在 四个基本点的连线上。那我把每个基本点连线的角度求出来 ,到时候 在进行角度翻转到垂直后 再求每个条数据所占当前基本点连线的占比不就行了?
/** * @description: 求3点之间角度 * @return {*} 点 a 的角度 * @author: 舒冬冬 */ angle(a, b, c) { const a = { x: a[0], y: a[1] } const b = { x: b[0], y: b[1] } const c = { x: c[0], y: c[1] } const ab = math.sqrt(math.pow(a.x - b.x, 2) + math.pow(a.y - b.y, 2)) const ac = math.sqrt(math.pow(a.x - c.x, 2) + math.pow(a.y - c.y, 2)) const bc = math.sqrt(math.pow(b.x - c.x, 2) + math.pow(b.y - c.y, 2)) const cosa = (math.pow(ab, 2) + math.pow(ac, 2) - math.pow(bc, 2)) / (2 * ab * ac) const anglea = math.round((math.acos(cosa) * 180) / math.pi) return anglea }
计算各个数据点的位置
接下来就是确定每条数据的 绘画范围了
我们先把金字塔左边和有右边旋转垂直后的点的位置确定下来
/** * @description: 根据a点旋转指定角度后b点的坐标位置 * @param {*} ptsrc 圆上某点(初始点); * @param {*} ptrotationcenter 圆心点 * @param {*} angle 旋转角度° -- [angle * m_pi / 180]:将角度换算为弧度 * 【注意】angle 逆时针为正,顺时针为负 * @return {*} * @author: 舒冬冬 */ rotatepoint(ptsrc, ptrotationcenter, angle) { const a = ptrotationcenter[0] const b = ptrotationcenter[1] const x0 = ptsrc[0] const y0 = ptsrc[1] const rx = a + (x0 - a) * math.cos((angle * math.pi) / 180) - (y0 - b) * math.sin((angle * math.pi) / 180) const ry = b + (x0 - a) * math.sin((angle * math.pi) / 180) + (y0 - b) * math.cos((angle * math.pi) / 180) const point = [rx, ry] return point },
const lp = this.rotatepoint(this.point.left, this.point.top, this.topangle.ltb * -1) const rp = this.rotatepoint(this.point.right, this.point.top, this.topangle.rtb)
lp 为 tl 的边 逆时针旋转 ltb 角度后的 点的位置
rp 为 tr 的边 顺时针旋转 rtb 角度后的 点的位置
这样就可以确定 每个数据点在 三条边上的各自所占长度了 完整代码
每个点的长度计算思路, 以在tl边上点为例:
拿到 lp (逆时针旋转 ltb角度后的位置)长度,根据数据所占总数据占比 求出该条数据的长度 再把角度转回去还原该边 就能拿到该条数据再 tl 边的上的位置信息。const vertical = [ this.point.top[0], (lp[1] - this.point.top[1]) * (item.accounted / 100) + this.point.top[1] ]
/** * @description: 计算数据的点位置 * @param {*} val 点占比 * @return {*} * @author: 舒冬冬 */ calculationpointposition(val) { const lp = this.rotatepoint(this.point.left, this.point.top, this.topangle.ltb * -1) const rp = this.rotatepoint(this.point.right, this.point.top, this.topangle.rtb) let temporary = { left: [ [0, 0], [0, 0], [0, 0] ], right: [ [0, 0], [0, 0], [0, 0] ], middle: [ [0, 0], [0, 0], [0, 0] ] } const datainfo = val.map((item, index) => { if (index === 0) { for (const key in temporary) { if (key === 'left') { // 垂直后点的位置 // 垂直后点点距离 const vertical = [ this.point.top[0], (lp[1] - this.point.top[1]) * (item.accounted / 100) + this.point.top[1] ] // 还原后点的位置 temporary.left = [this.point.top, this.rotatepoint(vertical, this.point.top, this.topangle.ltb), vertical] } else if (key === 'right') { // 垂直后点点距离 const vertical = [ this.point.top[0], (rp[1] - this.point.top[1]) * (item.accounted / 100) + this.point.top[1] ] // 还原后点的位置 temporary.right = [ this.point.top, this.rotatepoint(vertical, this.point.top, this.topangle.rtb * -1), vertical ] } else if (key === 'middle') { // 垂直后点点距离 temporary.middle = [ this.point.top, [ this.point.top[0], (this.point.bottom[1] - this.point.top[1]) * (item.accounted / 100) + this.point.top[1] ], [ this.point.top[0], (this.point.bottom[1] - this.point.top[1]) * (item.accounted / 100) + this.point.top[1] ] ] } } } else { for (const key in temporary) { const vertical = json.parse(json.stringify(temporary[key][2])) if (key === 'left') { // 垂直后点点距离 const vertical1 = [this.point.top[0], vertical[1] + (lp[1] - this.point.top[1]) * (item.accounted / 100)] // 还原后点的位置 temporary.left = [ this.point.top, this.rotatepoint(vertical1, this.point.top, this.topangle.ltb), vertical1 ] } else if (key === 'right') { // 垂直后点点距离 const vertical1 = [this.point.top[0], vertical[1] + (rp[1] - this.point.top[1]) * (item.accounted / 100)] // 还原后点的位置 temporary.right = [ this.point.top, this.rotatepoint(vertical1, this.point.top, this.topangle.rtb * -1), vertical1 ] } else if (key === 'middle') { temporary.middle = [ this.point.top, [this.point.top[0], (this.point.bottom[1] - this.point.top[1]) * (item.accounted / 100) + vertical[1]], [this.point.top[0], (this.point.bottom[1] - this.point.top[1]) * (item.accounted / 100) + vertical[1]] ] } } } return { ...item, temporary: json.parse(json.stringify(temporary)) } }) this.datainfo = datainfo },
这样就拿到了每个数据在每一条边上所占长度的点位。
绘画
数据图层绘画
我们虽然拿到了每个数据在每一条边上所占长度的点位。 那怎么获取这条数据在该边上的所在的线段长度呢?
很简单 因为 第一条数据的在该边长度的第二个点的位置就是第二条数据的第一个点的位置
现在就可以进行下一步。
数据 图层的绘画了
/** * @description: 数据图层绘画 * @param {*} * @return {*} * @author: 舒冬冬 */ paintdatainfo() { // let data = json.parse(json.stringify(this.datainfo)) // data.reverse() var index = -1 this.datainfo = this.datainfo.map(item => { index++ if (this.integration.color.length === index) { index = 0 } return { ...item, color: this.integration.color[index] } }) this.datainfo = this.datainfo.map((item, index) => { let drawingpoint = [] this.ctx.fillstyle = item.color this.ctx.beginpath() let point1, point2, point3, point4, point5, point6 if (index === 0) { [point1, point2, point3, point4, point5, point6] = [ item.temporary.left[0], item.temporary.left[1], item.temporary.middle[1], item.temporary.right[1], item.temporary.right[0], item.temporary.middle[0] ] } else { [point1, point2, point3, point4, point5, point6] = [ this.datainfo[index - 1].temporary.left[1], item.temporary.left[1], item.temporary.middle[1], item.temporary.right[1], this.datainfo[index - 1].temporary.right[1], this.datainfo[index - 1].temporary.middle[1] ] } this.ctx.moveto(...point1) this.ctx.lineto(...point2) this.ctx.lineto(...point3) this.ctx.lineto(...point4) this.ctx.lineto(...point5) this.ctx.lineto(...point6) drawingpoint = [point1, point2, point3, point4, point5, point6] if (this.integration.infostyle.stroke) { this.ctx.shadowoffsetx = 0 this.ctx.shadowoffsety = 0 this.ctx.shadowblur = 2 this.ctx.shadowcolor = this.integration.infostyle.strokecolor } this.ctx.fill() return { ...item, drawingpoint } }) }
以上就基本完成 金字塔图的核心内容了。
但是还是不够, 想要达到echarts的简单的功能,单单有图是不行的
文字的绘画
字体绘画就比较简单了, 我们拥有每一个数据的点的位置,把每个数据点的 f c 两个点的长度 除2 的点的位置设为起点就行了
/** * @description: 绘画字体 * 此方法请在 paintdatainfo() 执行后使用 * @param {*} * @return {*} * @author: 舒冬冬 */ paintingtext(ldata) { this.ctx.shadowcolor = 'rgba(90,90,90,0)' const color = this.integration.infostyle.color ? this.integration.infostyle.color : '#fff' const width = this.integration.infostyle.width ? this.integration.infostyle.width : 0 const dotsize = this.integration.infostyle.dotsize ? this.integration.infostyle.dotsize : 4 const offset = this.integration.infostyle.offset ? this.integration.infostyle.offset : [0, 0] let text = '' this.ctx.strokestyle = color this.ctx.fillstyle = color this.datainfo.foreach((item, index) => { if (item.drawingpoint) { let line = [ [0, 0], [0, 0] ] this.ctx.font = `normal lighter ${ this.integration.infostyle.size ? this.integration.infostyle.size : 14 }px sans-serif ` this.ctx.beginpath() if (ldata && index + 1 === ldata.l) { line = [ [ ldata.obj.drawingpoint[2][0], (ldata.obj.drawingpoint[2][1] - ldata.obj.drawingpoint[5][1]) / 2 + ldata.obj.drawingpoint[5][1] ], [ ldata.obj.drawingpoint[2][0] + ldata.obj.drawingpoint[2][0] / 2 + width, (ldata.obj.drawingpoint[2][1] - ldata.obj.drawingpoint[5][1]) / 2 + ldata.obj.drawingpoint[5][1] ] ] this.ctx.font = `normal lighter ${ this.integration.infostyle.size ? this.integration.infostyle.size + 2 : 16 }px sans-serif ` text = this.integration.fontformatter(item) !== 'default' ? this.integration.fontformatter(item) : ldata.obj.value + ' ---- ' + ldata.obj.name this.ctx.setlinedash([0, 0]) this.ctx.stroketext( text, line[1][0] + offset[0], line[1][1] + (this.integration.infostyle.size ? this.integration.infostyle.size + 2 : 14) / 3 + offset[1] ) } else { line = [ [ item.drawingpoint[2][0], (item.drawingpoint[2][1] - item.drawingpoint[5][1]) / 2 + item.drawingpoint[5][1] ], [ item.drawingpoint[2][0] + item.drawingpoint[2][0] / 2 + width, (item.drawingpoint[2][1] - item.drawingpoint[5][1]) / 2 + item.drawingpoint[5][1] ] ] text = this.integration.fontformatter(item) !== 'default' ? this.integration.fontformatter(item) : item.value + ' ----- ' + item.name this.ctx.setlinedash([0, 0]) this.ctx.stroketext( text, line[1][0] + offset[0], line[1][1] + (this.integration.infostyle.size ? this.integration.infostyle.size + 2 : 16) / 3 + offset[1] ) } this.ctx.setlinedash(this.integration.infostyle.setlinedash) this.ctx.moveto(...line[0]) this.ctx.lineto(...line[1]) this.ctx.stroke() this.ctx.arc(...line[0], dotsize, 0, 360, false) this.ctx.fill() //画实心圆 } else { throw '未找到 drawingpoint 属性' } }) },
高亮图层
高亮图层无非就是监听鼠标移入位置,并且判断鼠标移入位置是否存在图层内,在哪个图层内,然后重新绘画当前图层
/** * @description: 鼠标事件注册 * @param {*} * @return {*} * @author: 舒冬冬 */ eventregistered() { const canvaswarpper = document.getelementbyid('canvas-warpper') //注册事件 canvaswarpper.addeventlistener('mousedown', this.domousedown, false) canvaswarpper.addeventlistener('mouseup', this.domouseup, false) canvaswarpper.addeventlistener('mousemove', this.domousemove, false) // //注册事件 // this.canvas.addeventlistener('mousedown', this.domousedown, false) // this.canvas.addeventlistener('mouseup', this.domouseup, false) // this.canvas.addeventlistener('mousemove', this.domousemove, false) }, /** * @description: 鼠标移动 * @param {*} e * @return {*} * @author: 舒冬冬 */ // eslint-disable-next-line no-unused-vars domousemove(e) { const x = e.pagex const y = e.pagey this.highlightcurrentregion(this.determinedatamouse(this.getlocation(x, y))) if (this.integration.tooltip.show) { this.showtooltip(this.determinedatamouse(this.getlocation(x, y)), this.getlocation(x, y)) } }, /** * @description: 判断鼠标在哪层位置上 * @param {*} * @return {*} * @author: 舒冬冬 */ determinedatamouse(mouselocation) { let req = false for (let index = 0; index < this.datainfo.length; index++) { if (this.insidepolygon(this.datainfo[index].drawingpoint, mouselocation)) { return (req = { l: index + 1, obj: this.datainfo[index] }) } } return req }, /** * @description: 高亮某一层级 * @param {*} ldata 层级数据 * @return {*} * @author: 舒冬冬 */ highlightcurrentregion(ldata) { // const width = this.canvas.width; // this.canvas.width = width; this.ctx.clearrect(0, 0, this.canvas.width, this.canvas.height) if (!ldata) { this.paintdatainfo() this.ctx.shadowcolor = 'rgba(90,90,90,0)' this.paintingbody() this.paintingtext() return } this.paintdatainfo() this.ctx.shadowcolor = 'rgba(90,90,90,0)' this.paintingbody() this.ctx.fillstyle = ldata.obj.color // this.ctx.scale(1.05, 1.05) this.ctx.beginpath() this.ctx.moveto(ldata.obj.drawingpoint[0][0], ldata.obj.drawingpoint[0][1]) this.ctx.lineto(ldata.obj.drawingpoint[1][0], ldata.obj.drawingpoint[1][1]) this.ctx.lineto(ldata.obj.drawingpoint[2][0], ldata.obj.drawingpoint[2][1]) this.ctx.lineto(ldata.obj.drawingpoint[3][0], ldata.obj.drawingpoint[3][1]) this.ctx.lineto(ldata.obj.drawingpoint[4][0], ldata.obj.drawingpoint[4][1]) this.ctx.lineto(ldata.obj.drawingpoint[5][0], ldata.obj.drawingpoint[5][1]) this.ctx.shadowoffsetx = 0 this.ctx.shadowoffsety = 0 this.ctx.shadowblur = 10 this.ctx.shadowcolor = this.integration.infostyle.highlightedcolor this.ctx.fill() // 阴影绘制 this.ctx.beginpath() this.ctx.moveto(ldata.obj.drawingpoint[0][0], ldata.obj.drawingpoint[0][1]) this.ctx.lineto(ldata.obj.drawingpoint[1][0], ldata.obj.drawingpoint[1][1]) this.ctx.lineto(ldata.obj.drawingpoint[2][0], ldata.obj.drawingpoint[2][1]) this.ctx.lineto(ldata.obj.drawingpoint[5][0], ldata.obj.drawingpoint[5][1]) this.ctx.fillstyle = 'rgba(120,120,120,.15)' this.ctx.fill() this.paintingtext(ldata) }
显示tooltip位置
可以先定义 tooltip 的渲染模板
然后在代码上进行渲染
showtooltip(ldata, coordinates) { let canvaswarpper = document.getelementbyid('canvas-warpper') let canvastooltip = document.getelementbyid('canvas-tooltip') if (ldata) { canvastooltip.style.zindex = this.integration.tooltip.z canvastooltip.style.transition = ' opacity 0.2s cubic-bezier(0.23, 1, 0.32, 1) 0s, visibility 0.2s cubic-bezier(0.23, 1, 0.32, 1) 0s,transform 0.15s' let html = json.parse(json.stringify(this.tooltipdiv)) if (this.integration.tooltip.formatter) { html = this.integration.tooltip.formatter(ldata) } else { const searchval = [ ['$[title]$', ldata.obj.title], ['$[name]$', ldata.obj.name], ['$[val]$', ldata.obj.value], ['$[color]$', ldata.obj.color], ['$[fontsize]$', this.integration.tooltip.fontsize], ['$[backgroundcolor]$', this.integration.tooltip.backgroundcolor], ['$[fontcolor]$', this.integration.tooltip.fontcolor] ] searchval.foreach(el => { html = html.replaceall(...el) }) } canvastooltip.innerhtml = html canvaswarpper.style.cursor = 'pointer' canvastooltip.style.visibility = 'visible' canvastooltip.style.opacity = 1 let [x, y] = coordinates x = x + 20 y = y + 20 // 画布高度 // canvasheight: 0, // 画布宽度 // canvaswidth: 0, // 判断是否超出框架内容 if (x + canvastooltip.clientwidth > this.canvaswidth) { x = x - canvastooltip.clientwidth - 40 } if (y + canvastooltip.clientheight > this.canvasheight) { y = y - canvastooltip.clientheight - 40 } canvastooltip.style.transform = `translate3d(${x}px, ${y}px, 0px)` } else { canvaswarpper.style.cursor = 'default' canvastooltip.style.visibility = 'hidden' canvastooltip.style.opacity = 0 } },
而一些其他的配置功能呢也是比较简单的操作了,主要是太懒了????,
直接上完整源码吧! 源码上注释也比较全,不是很清楚的可以评论,我看到会回复的!
完整源码
<template> <div id="canvas-warpper"> <div id="canvas-tooltip"></div> </div> </template> <script> export default { name: 'pyramid', props: { options: { type: object, default: () => { return { title: '', // 主体离边框距离 distance: [0, 0], // 主体偏移值 (x,y) offset: [0, 0], // 排序(max , min)优先 sort: '', // 颜色 color: ['#80ffa5', '#00ddff', '#37a2ff', '#ff0087', '#ffbf00'], // 格式化字体输出 fontformatter: () => { return 'default' }, // tooltip信息配置 tooltip: { show: true, // 是否显示 fontcolor: '#000', // 字体内部颜色 fontsize: 14, // 字体大小 backgroundcolor: '#fff', // tooltip背景 formatter: null, // 回调方法 z: 999999 // tooltip z-index层级 }, // 样式 infostyle: { stroke: false, // 是否描边 strokecolor: '#fff', //描边颜色 size: null, // 字体大小 color: null, //颜色 highlightedcolor: '#fff', // 高亮颜色 setlinedash: [0, 0], // 虚线值 width: -10, // 设置多少 就会在基础上加上设置的值 offset: [0, 0], // 字体x,y的偏移度 dotsize: 4 //点大小 } } } }, // 渲染数据 data: { type: array, default: () => { return [ { name: 'name1', value: 11 }, { name: 'name2', value: 11 }, { name: 'name3', value: 11 }, { name: 'name4', value: 77 }, { name: 'name5', value: 55 }, { name: 'name6', value: 66 } ] } } }, watch: { data: { immediate: true, deep: true, handler(newvalue) { // 数据总量 let totaldata = 0 newvalue.foreach(element => { totaldata = totaldata + number(element.value) }) this.datainfo = newvalue.map(item => { const accounted = (item.value / totaldata) * 100 return { ...item, accounted, title: this.integration.title } }) if (this.integration.sort === 'max') { this.datainfo.sort((a, b) => { return a.value - b.value }) } else if (this.integration.sort === 'min') { this.datainfo.sort((a, b) => { return b.value - a.value }) } } } }, computed: { integration() { return { title: this.options.title ? this.options.title : '', // 主体离边框距离 distance: this.options.distance ? this.options.distance : [0, 0], // 主体偏移值 (x,y) offset: this.options.offset ? this.options.offset : [0, 0], // 排序(max , min)优先 sort: this.options.sort ? this.options.sort : '', // 颜色 color: this.options.color ? this.options.color : ['#80ffa5', '#00ddff', '#37a2ff', '#ff0087', '#ffbf00'], // 格式化字体输出 fontformatter: this.options.fontformatter ? this.options.fontformatter : () => { return 'default' }, // tooltip显示 tooltip: { show: this.options.tooltip ? (this.options.tooltip.show ? this.options.tooltip.show : true) : true, // 是否显示 fontcolor: this.options.tooltip ? this.options.tooltip.fontcolor ? this.options.tooltip.fontcolor : '#000' : '#000', // 字体内部颜色 fontsize: this.options.tooltip ? (this.options.tooltip.fontsize ? this.options.tooltip.fontsize : 14) : 14, // 字体大小 backgroundcolor: this.options.tooltip ? this.options.tooltip.backgroundcolor ? this.options.tooltip.backgroundcolor : '#fff' : '#fff', // tooltip背景 formatter: this.options.tooltip ? this.options.tooltip.formatter ? this.options.tooltip.formatter : null : null, // 返回方法 z: this.options.tooltip ? (this.options.tooltip.z ? this.options.tooltip.z : 999999) : 999999 // tooltip z-index层级 }, // 样式 infostyle: { stroke: this.options.infostyle ? this.options.infostyle.stroke ? this.options.infostyle.stroke : false : false, //是否描边 strokecolor: this.options.infostyle ? this.options.infostyle.strokecolor ? this.options.infostyle.strokecolor : '#fff' : '#fff', // 描边颜色 size: this.options.infostyle ? (this.options.infostyle.size ? this.options.infostyle.size : null) : null, // 字体大小 color: this.options.infostyle ? (this.options.infostyle.color ? this.options.infostyle.color : null) : null, //颜色 width: this.options.infostyle ? this.options.infostyle.width || this.options.infostyle.width !== 0 ? this.options.infostyle.width : -10 : -10, // 设置多少 就会在基础上加上设置的值 offset: this.options.infostyle ? this.options.infostyle.offset ? this.options.infostyle.offset : [0, 0] : [0, 0], // 字体x,y的偏移度 setlinedash: this.options.infostyle ? this.options.infostyle.setlinedash ? this.options.infostyle.setlinedash : [0, 0] : [0, 0], //虚线值 highlightedcolor: this.options.infostyle ? this.options.infostyle.highlightedcolor ? this.options.infostyle.highlightedcolor : '#fff' : '#fff', //高亮颜色 dotsize: this.options.infostyle ? this.options.infostyle.dotsize || this.options.infostyle.dotsize !== 0 ? this.options.infostyle.dotsize : 4 : 4 //点大小 } } } }, data() { return { // canvas 主体 canvas: null, // 图像渲染内容 ctx: null, // 画布高度 canvasheight: 0, // 画布宽度 canvaswidth: 0, // 画布中心点 [x,y] canvascenter: [0, 0], // 金字塔四个点位置 point: { top: [0, 0], left: [0, 0], right: [0, 0], bottom: [0, 0], shadow: [0, 0] }, // 数据信息 datainfo: [], // 金字塔顶端角度信息 topangle: { ltb: 0, rtb: 0 }, // tooltip 模板 tooltipdiv: `<div style="margin: 0px 0 0; line-height: 1;border-color: $[backgroundcolor]$ ;background-color: $[backgroundcolor]$;color: $[fontcolor]$; border-width: 1px;border-radius: 4px;padding: 10px;pointer-events: none;box-shadow: rgb(0 0 0 / 20%) 1px 2px 10px;border-style: solid;white-space: nowrap;"> <div style="margin: 0px 0 0; line-height: 1"> <div style="font-size: $[fontsize]$px; color: $[fontcolor]$; font-weight: 400; line-height: 1"> $[title]$ </div> <div style="margin: 10px 0 0; line-height: 1"> <div style="margin: 0px 0 0; line-height: 1"> <div style="margin: 0px 0 0; line-height: 1"> <span style=" display: inline-block; margin-right: 4px; border-radius: 10px; width: 10px; height: 10px; background-color: $[color]$; " ></span> <span style="font-size: $[fontsize]$px; color: $[fontcolor]$; font-weight: 400; margin-left: 2px">$[name]$</span> <span style="float: right; margin-left: 20px; font-size: $[fontsize]$px; color: $[fontcolor]$; font-weight: 900">$[val]$</span> <div style="clear: both"></div> </div> <div style="clear: both"></div> </div> <div style="clear: both"></div> </div> <div style="clear: both"></div> </div> <div style="clear: both"></div> </div>` } }, mounted() { this.init() }, methods: { init() { this.initcanvasbaseinfo() this.paintdatainfo() this.paintingtext() this.paintingbody() this.eventregistered() }, /** * @description: 初始化canvas基本信息 * @param {*} * @return {*} * @author: 舒冬冬 */ initcanvasbaseinfo() { let el = document.getelementbyid('canvas-warpper') // 创建canvas元素 this.canvas = document.createelement('canvas') // 把canvas元素节点添加在el元素下 el.appendchild(this.canvas) this.canvaswidth = el.offsetwidth this.canvasheight = el.offsetheight // 将canvas元素设置与父元素同宽 this.canvas.setattribute('width', this.canvaswidth) // 将canvas元素设置与父元素同高 this.canvas.setattribute('height', this.canvasheight) this.canvascenter = [ math.round((this.canvaswidth - this.integration.distance[0] * 2) / 2) + this.integration.distance[0], math.round((this.canvasheight - this.integration.distance[1] * 2) / 2) + this.integration.distance[1] ] if (this.canvas.getcontext) { this.ctx = this.canvas.getcontext('2d') // 金字塔基本点位置 this.point.top = [this.canvascenter[0] - this.canvaswidth / 13, this.integration.distance[1]] this.point.left = [ this.integration.distance[0] * 1.5, this.canvasheight - this.integration.distance[1] - this.canvasheight / 5 ] this.point.right = [ this.canvaswidth - this.integration.distance[0] * 1.9, this.canvasheight - this.integration.distance[1] - this.canvasheight / 5 ] this.point.bottom = [ this.canvascenter[0] - this.canvaswidth / 13, this.canvasheight - this.integration.distance[1] ] this.point.shadow = [ this.integration.distance[0] - this.canvascenter[0] / 5, this.canvasheight / 1.2 - this.integration.distance[1] ] for (const key in this.point) { this.point[key][0] = this.point[key][0] + this.integration.offset[0] this.point[key][1] = this.point[key][1] + this.integration.offset[1] } } else { throw 'canvas下未找到 getcontext方法' } this.topangle.ltb = this.angle(this.point.top, this.point.left, this.point.bottom) this.topangle.rtb = this.angle(this.point.top, this.point.right, this.point.bottom) // 计算各数据点位置 this.calculationpointposition(this.datainfo) }, // ======================================事件========================================== /** * @description: 鼠标事件注册 * @param {*} * @return {*} * @author: 舒冬冬 */ eventregistered() { const canvaswarpper = document.getelementbyid('canvas-warpper') //注册事件 canvaswarpper.addeventlistener('mousedown', this.domousedown, false) canvaswarpper.addeventlistener('mouseup', this.domouseup, false) canvaswarpper.addeventlistener('mousemove', this.domousemove, false) // //注册事件 // this.canvas.addeventlistener('mousedown', this.domousedown, false) // this.canvas.addeventlistener('mouseup', this.domouseup, false) // this.canvas.addeventlistener('mousemove', this.domousemove, false) }, /** * @description: 鼠标按下 * @param {*} e * @return {*} * @author: 舒冬冬 */ // eslint-disable-next-line no-unused-vars domousedown(e) {}, /** * @description: 鼠标弹起 * @param {*} e * @return {*} * @author: 舒冬冬 */ // eslint-disable-next-line no-unused-vars domouseup(e) {}, /** * @description: 鼠标移动 * @param {*} e * @return {*} * @author: 舒冬冬 */ // eslint-disable-next-line no-unused-vars domousemove(e) { const x = e.pagex const y = e.pagey this.highlightcurrentregion(this.determinedatamouse(this.getlocation(x, y))) if (this.integration.tooltip.show) { this.showtooltip(this.determinedatamouse(this.getlocation(x, y)), this.getlocation(x, y)) } }, /** * @description 判断一个点是否在多边形内部 * @param points 多边形坐标集合 * @param testpoint 测试点坐标 * @author: 舒冬冬 * 返回true为真,false为假 */ insidepolygon(points, testpoint) { const x = testpoint[0], y = testpoint[1] let inside = false for (let i = 0, j = points.length - 1; i < points.length; j = i++) { const xi = points[i][0], yi = points[i][1] const xj = points[j][0], yj = points[j][1] const intersect = yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi if (intersect) inside = !inside } return inside }, /** * @description: 获取当前鼠标坐标 * @param {*} * @return {*} * @author: 舒冬冬 */ getlocation(x, y) { const bbox = this.canvas.getboundingclientrect() return [(x - bbox.left) * (this.canvas.width / bbox.width), (y - bbox.top) * (this.canvas.height / bbox.height)] }, // ======================================算法========================================== /** * @description: 根据a点旋转指定角度后b点的坐标位置 * @param {*} ptsrc 圆上某点(初始点); * @param {*} ptrotationcenter 圆心点 * @param {*} angle 旋转角度° -- [angle * m_pi / 180]:将角度换算为弧度 * 【注意】angle 逆时针为正,顺时针为负 * @return {*} * @author: 舒冬冬 */ rotatepoint(ptsrc, ptrotationcenter, angle) { const a = ptrotationcenter[0] const b = ptrotationcenter[1] const x0 = ptsrc[0] const y0 = ptsrc[1] const rx = a + (x0 - a) * math.cos((angle * math.pi) / 180) - (y0 - b) * math.sin((angle * math.pi) / 180) const ry = b + (x0 - a) * math.sin((angle * math.pi) / 180) + (y0 - b) * math.cos((angle * math.pi) / 180) const point = [rx, ry] return point }, /** * @description: 求3点之间角度 * @return {*} 点 a 的角度 * @author: 舒冬冬 */ angle(a, b, c) { const a = { x: a[0], y: a[1] } const b = { x: b[0], y: b[1] } const c = { x: c[0], y: c[1] } const ab = math.sqrt(math.pow(a.x - b.x, 2) + math.pow(a.y - b.y, 2)) const ac = math.sqrt(math.pow(a.x - c.x, 2) + math.pow(a.y - c.y, 2)) const bc = math.sqrt(math.pow(b.x - c.x, 2) + math.pow(b.y - c.y, 2)) const cosa = (math.pow(ab, 2) + math.pow(ac, 2) - math.pow(bc, 2)) / (2 * ab * ac) const anglea = math.round((math.acos(cosa) * 180) / math.pi) return anglea }, /** * @description: 计算两点之间距离 * @return {*} * @author: 舒冬冬 */ getdistancebetweentwopoints(a, b) { const a = a[0] - b[0] const b = a[1] - b[1] const result = math.sqrt(math.pow(a, 2) + math.pow(b, 2)) return result }, /** * @description: 计算数据的点位置 * @param {*} val 点占比 * @return {*} * @author: 舒冬冬 */ calculationpointposition(val) { const lp = this.rotatepoint(this.point.left, this.point.top, this.topangle.ltb * -1) const rp = this.rotatepoint(this.point.right, this.point.top, this.topangle.rtb) let temporary = { left: [ [0, 0], [0, 0], [0, 0] ], right: [ [0, 0], [0, 0], [0, 0] ], middle: [ [0, 0], [0, 0], [0, 0] ] } const datainfo = val.map((item, index) => { if (index === 0) { for (const key in temporary) { if (key === 'left') { // 垂直后点的位置 // 垂直后点点距离 const vertical = [ this.point.top[0], (lp[1] - this.point.top[1]) * (item.accounted / 100) + this.point.top[1] ] // 还原后点的位置 temporary.left = [this.point.top, this.rotatepoint(vertical, this.point.top, this.topangle.ltb), vertical] } else if (key === 'right') { // 垂直后点点距离 const vertical = [ this.point.top[0], (rp[1] - this.point.top[1]) * (item.accounted / 100) + this.point.top[1] ] // 还原后点的位置 temporary.right = [ this.point.top, this.rotatepoint(vertical, this.point.top, this.topangle.rtb * -1), vertical ] } else if (key === 'middle') { // 垂直后点点距离 temporary.middle = [ this.point.top, [ this.point.top[0], (this.point.bottom[1] - this.point.top[1]) * (item.accounted / 100) + this.point.top[1] ], [ this.point.top[0], (this.point.bottom[1] - this.point.top[1]) * (item.accounted / 100) + this.point.top[1] ] ] } } } else { for (const key in temporary) { const vertical = json.parse(json.stringify(temporary[key][2])) if (key === 'left') { // 垂直后点点距离 const vertical1 = [this.point.top[0], vertical[1] + (lp[1] - this.point.top[1]) * (item.accounted / 100)] // 还原后点的位置 temporary.left = [ this.point.top, this.rotatepoint(vertical1, this.point.top, this.topangle.ltb), vertical1 ] } else if (key === 'right') { // 垂直后点点距离 const vertical1 = [this.point.top[0], vertical[1] + (rp[1] - this.point.top[1]) * (item.accounted / 100)] // 还原后点的位置 temporary.right = [ this.point.top, this.rotatepoint(vertical1, this.point.top, this.topangle.rtb * -1), vertical1 ] } else if (key === 'middle') { temporary.middle = [ this.point.top, [this.point.top[0], (this.point.bottom[1] - this.point.top[1]) * (item.accounted / 100) + vertical[1]], [this.point.top[0], (this.point.bottom[1] - this.point.top[1]) * (item.accounted / 100) + vertical[1]] ] } } } return { ...item, temporary: json.parse(json.stringify(temporary)) } }) this.datainfo = datainfo }, /** * @description: 判断鼠标在哪层位置上 * @param {*} * @return {*} * @author: 舒冬冬 */ determinedatamouse(mouselocation) { let req = false for (let index = 0; index < this.datainfo.length; index++) { if (this.insidepolygon(this.datainfo[index].drawingpoint, mouselocation)) { return (req = { l: index + 1, obj: this.datainfo[index] }) } } return req }, // ======================================绘图========================================== /** * @description: 绘画主体 * @param {*} * @return {*} * @author: 舒冬冬 */ paintingbody() { // 左半边金字塔阴影 this.ctx.fillstyle = 'rgba(120,120,120,.15)' this.ctx.beginpath() this.ctx.moveto(...this.point.top) this.ctx.lineto(...this.point.bottom) this.ctx.lineto(...this.point.left) this.ctx.fill() this.ctx.fill() }, /** * @description: 数据图层绘画 * @param {*} * @return {*} * @author: 舒冬冬 */ paintdatainfo() { var index = -1 this.datainfo = this.datainfo.map(item => { index++ if (this.integration.color.length === index) { index = 0 } return { ...item, color: this.integration.color[index] } }) this.datainfo = this.datainfo.map((item, index) => { let drawingpoint = [] this.ctx.fillstyle = item.color this.ctx.beginpath() let point1, point2, point3, point4, point5, point6 if (index === 0) { [point1, point2, point3, point4, point5, point6] = [ item.temporary.left[0], item.temporary.left[1], item.temporary.middle[1], item.temporary.right[1], item.temporary.right[0], item.temporary.middle[0] ] } else { [point1, point2, point3, point4, point5, point6] = [ this.datainfo[index - 1].temporary.left[1], item.temporary.left[1], item.temporary.middle[1], item.temporary.right[1], this.datainfo[index - 1].temporary.right[1], this.datainfo[index - 1].temporary.middle[1] ] } this.ctx.moveto(...point1) this.ctx.lineto(...point2) this.ctx.lineto(...point3) this.ctx.lineto(...point4) this.ctx.lineto(...point5) this.ctx.lineto(...point6) drawingpoint = [point1, point2, point3, point4, point5, point6] if (this.integration.infostyle.stroke) { this.ctx.shadowoffsetx = 0 this.ctx.shadowoffsety = 0 this.ctx.shadowblur = 2 this.ctx.shadowcolor = this.integration.infostyle.strokecolor } this.ctx.fill() return { ...item, drawingpoint } }) }, /** * @description: 绘画字体 * 此方法请在 paintdatainfo() 执行后使用 * @param {*} * @return {*} * @author: 舒冬冬 */ paintingtext(ldata) { this.ctx.shadowcolor = 'rgba(90,90,90,0)' const color = this.integration.infostyle.color ? this.integration.infostyle.color : '#fff' const width = this.integration.infostyle.width ? this.integration.infostyle.width : 0 const dotsize = this.integration.infostyle.dotsize ? this.integration.infostyle.dotsize : 4 const offset = this.integration.infostyle.offset ? this.integration.infostyle.offset : [0, 0] let text = '' this.ctx.strokestyle = color this.ctx.fillstyle = color this.datainfo.foreach((item, index) => { if (item.drawingpoint) { let line = [ [0, 0], [0, 0] ] this.ctx.font = `normal lighter ${ this.integration.infostyle.size ? this.integration.infostyle.size : 14 }px sans-serif ` this.ctx.beginpath() if (ldata && index + 1 === ldata.l) { line = [ [ ldata.obj.drawingpoint[2][0], (ldata.obj.drawingpoint[2][1] - ldata.obj.drawingpoint[5][1]) / 2 + ldata.obj.drawingpoint[5][1] ], [ ldata.obj.drawingpoint[2][0] + ldata.obj.drawingpoint[2][0] / 2 + width, (ldata.obj.drawingpoint[2][1] - ldata.obj.drawingpoint[5][1]) / 2 + ldata.obj.drawingpoint[5][1] ] ] this.ctx.font = `normal lighter ${ this.integration.infostyle.size ? this.integration.infostyle.size + 2 : 16 }px sans-serif ` text = this.integration.fontformatter(item) !== 'default' ? this.integration.fontformatter(item) : ldata.obj.value + ' ---- ' + ldata.obj.name this.ctx.setlinedash([0, 0]) this.ctx.stroketext( text, line[1][0] + offset[0], line[1][1] + (this.integration.infostyle.size ? this.integration.infostyle.size + 2 : 14) / 3 + offset[1] ) } else { line = [ [ item.drawingpoint[2][0], (item.drawingpoint[2][1] - item.drawingpoint[5][1]) / 2 + item.drawingpoint[5][1] ], [ item.drawingpoint[2][0] + item.drawingpoint[2][0] / 2 + width, (item.drawingpoint[2][1] - item.drawingpoint[5][1]) / 2 + item.drawingpoint[5][1] ] ] text = this.integration.fontformatter(item) !== 'default' ? this.integration.fontformatter(item) : item.value + ' ----- ' + item.name this.ctx.setlinedash([0, 0]) this.ctx.stroketext( text, line[1][0] + offset[0], line[1][1] + (this.integration.infostyle.size ? this.integration.infostyle.size + 2 : 16) / 3 + offset[1] ) } this.ctx.setlinedash(this.integration.infostyle.setlinedash) this.ctx.moveto(...line[0]) this.ctx.lineto(...line[1]) this.ctx.stroke() this.ctx.arc(...line[0], dotsize, 0, 360, false) this.ctx.fill() //画实心圆 } else { throw '未找到 drawingpoint 属性' } }) }, /** * @description: 显示tooltip位置 * @param {*} ldata 当前层级 * @param {*} coordinates 鼠标位置 * @return {*} * @author: 舒冬冬 */ showtooltip(ldata, coordinates) { let canvaswarpper = document.getelementbyid('canvas-warpper') let canvastooltip = document.getelementbyid('canvas-tooltip') if (ldata) { canvastooltip.style.zindex = this.integration.tooltip.z canvastooltip.style.transition = ' opacity 0.2s cubic-bezier(0.23, 1, 0.32, 1) 0s, visibility 0.2s cubic-bezier(0.23, 1, 0.32, 1) 0s,transform 0.15s' let html = json.parse(json.stringify(this.tooltipdiv)) if (this.integration.tooltip.formatter) { html = this.integration.tooltip.formatter(ldata) } else { const searchval = [ ['$[title]$', ldata.obj.title], ['$[name]$', ldata.obj.name], ['$[val]$', ldata.obj.value], ['$[color]$', ldata.obj.color], ['$[fontsize]$', this.integration.tooltip.fontsize], ['$[backgroundcolor]$', this.integration.tooltip.backgroundcolor], ['$[fontcolor]$', this.integration.tooltip.fontcolor] ] searchval.foreach(el => { html = html.replaceall(...el) }) } canvastooltip.innerhtml = html canvaswarpper.style.cursor = 'pointer' canvastooltip.style.visibility = 'visible' canvastooltip.style.opacity = 1 let [x, y] = coordinates x = x + 20 y = y + 20 // 画布高度 // canvasheight: 0, // 画布宽度 // canvaswidth: 0, // 判断是否超出框架内容 if (x + canvastooltip.clientwidth > this.canvaswidth) { x = x - canvastooltip.clientwidth - 40 } if (y + canvastooltip.clientheight > this.canvasheight) { y = y - canvastooltip.clientheight - 40 } canvastooltip.style.transform = `translate3d(${x}px, ${y}px, 0px)` } else { canvaswarpper.style.cursor = 'default' canvastooltip.style.visibility = 'hidden' canvastooltip.style.opacity = 0 } }, /** * @description: 高亮某一层级 * @param {*} ldata 层级数据 * @return {*} * @author: 舒冬冬 */ highlightcurrentregion(ldata) { this.ctx.clearrect(0, 0, this.canvas.width, this.canvas.height) if (!ldata) { this.paintdatainfo() this.ctx.shadowcolor = 'rgba(90,90,90,0)' this.paintingbody() this.paintingtext() return } this.paintdatainfo() this.ctx.shadowcolor = 'rgba(90,90,90,0)' this.paintingbody() this.ctx.fillstyle = ldata.obj.color // this.ctx.scale(1.05, 1.05) this.ctx.beginpath() this.ctx.moveto(ldata.obj.drawingpoint[0][0], ldata.obj.drawingpoint[0][1]) this.ctx.lineto(ldata.obj.drawingpoint[1][0], ldata.obj.drawingpoint[1][1]) this.ctx.lineto(ldata.obj.drawingpoint[2][0], ldata.obj.drawingpoint[2][1]) this.ctx.lineto(ldata.obj.drawingpoint[3][0], ldata.obj.drawingpoint[3][1]) this.ctx.lineto(ldata.obj.drawingpoint[4][0], ldata.obj.drawingpoint[4][1]) this.ctx.lineto(ldata.obj.drawingpoint[5][0], ldata.obj.drawingpoint[5][1]) this.ctx.shadowoffsetx = 0 this.ctx.shadowoffsety = 0 this.ctx.shadowblur = 10 this.ctx.shadowcolor = this.integration.infostyle.highlightedcolor this.ctx.fill() // 阴影绘制 this.ctx.beginpath() this.ctx.moveto(ldata.obj.drawingpoint[0][0], ldata.obj.drawingpoint[0][1]) this.ctx.lineto(ldata.obj.drawingpoint[1][0], ldata.obj.drawingpoint[1][1]) this.ctx.lineto(ldata.obj.drawingpoint[2][0], ldata.obj.drawingpoint[2][1]) this.ctx.lineto(ldata.obj.drawingpoint[5][0], ldata.obj.drawingpoint[5][1]) this.ctx.fillstyle = 'rgba(120,120,120,.15)' this.ctx.fill() this.paintingtext(ldata) } } } </script>
结尾
项目地址:(https://github.com/shdjason/pyramid.git)
到此这篇关于使用canvas仿echarts实现金字塔图的实例代码的文章就介绍到这了,更多相关canvas仿echarts金字塔图内容请搜索以前的文章或继续浏览下面的相关文章,希望大家以后多多支持!
上一篇: 基于HTML十秒做出淘宝页面