微信小程序绘制雷达图
demo.wxss
initRadarChart: function (averageList, referenceList) { averageList = [averageList[0], averageList[2], averageList[4], averageList[1], averageList[3]] const self = this const query = this.createSelectorQuery() query .select('.radarCanvas') .fields({ id: true, node: true, size: true }) .exec(async function (res) { console.log('res', res) const canvas = res[0].node // Canvas 绘制上下文 const context = canvas.getContext('2d') // 初始化画布大小 var mW = 750 // 宽高 var mH = 750 // 宽高 canvas.width = 750 canvas.height = 750 let length = 5 // 多少边 var x = mW / 2 //中心点 var y = mH / 2 //中心点 var center = { x: x, y: y } var radarMin = Math.min(x, y) * 1.5 var halfMin = radarMin / 2 var imgCenter = { x: center.x - halfMin, y: center.y - halfMin } // radarMin = radarMin * 1.5; var radius = halfMin * 0.909 //半径(减去的值用于给绘制的文本留空间) var angle = (Math.PI * 2) / length var data = [ { name: '实际值', value: averageList, color: 'rgba(167, 245, 231, 1)' } ] var step = 1 var MaxStep = 1 // 50 const image = canvas.createImage() // 等待图片加载 await new Promise(resolve => { image.onload = resolve image.src = 'https://storesong-file-uat.watsonsestore.com.cn/booking/87be86eb75ca4b5091bc579a1fba05c6.png' // 要加载的图片 url }) context.fillStyle = '#fff' context.fillRect(0, 0, mW, mH) // // context.drawImage(res.path, imgCenter.x, imgCenter.y, radarMin, radarMin) // context.save(); context.drawImage(image, imgCenter.x, imgCenter.y, radarMin, radarMin) // context.save(); var MaxValue = 100 data.forEach(function (val) { context.beginPath() context.strokeStyle = val.color var currentRad = (radius * val.value[0]) / MaxValue context.moveTo(center.x, center.y - currentRad) var currentAngle = -Math.PI / 2 for (var i = 0; i < length; i++) { currentRad = (radius * val.value[i]) / MaxValue context.lineTo(center.x + currentRad * Math.cos(currentAngle), center.y + currentRad * Math.sin(currentAngle)) currentAngle += angle } currentRad = (radius * val.value[0]) / MaxValue context.lineTo(center.x, center.y - currentRad) context.stroke() if (val.color) { context.fillStyle = val.color context.globalAlpha = 0.5 context.fill() } context.closePath() }) context.save() // 保存以上透明设置 context.globalAlpha = 1 // 将画布重新设置不透明 // 雷达图导出图片 setTimeout(() => { wx.canvasToTempFilePath({ canvas: canvas, success(res) { // console.log("res", res) wx.getFileSystemManager().readFile({ filePath: res.tempFilePath, //图片路径 encoding: 'base64', //编码格式 success: res => { // console.log('data:image/png;base64,' + res.data); //成功的回调 self.setData({ radarUrl: 'data:image/png;base64,' + res.data }) } }) } }) }, 500) }) }
demo.wxml
<canvas class="radarCanvas" type="2d" />