1.根据数据绘制饼图
/** 绘制环形图 */
const drawPieCharts = () => {const {canWithdrawalPriceFront,noWithdrawalPriceFront,haveWithdrawalPriceFront,} = this.state;const myCanvas = this.cavasRef.current;// @ts-ignoreconst ctx = myCanvas.getContext('2d');if (ctx) {//数据const data = [canWithdrawalPriceFront,noWithdrawalPriceFront,haveWithdrawalPriceFront,];/* 需要把数据转出弧度 先计算总数*/let total = 0;data.forEach((item) => {// @ts-ignoretotal += item;});if (total === 0) {return;}//计算每个数据所占的弧度const angleList: any = [];data.forEach((item) => {if (item !== 0) {// @ts-ignoreconst angle = Math.PI * 2 * (item / total);angleList.push(angle);} else {angleList.push(0);}});/* 颜色 */const colorArr = ['#5FE6E6', '#FFB356', '#69BAF8'];/** 圆心坐标 */const centerWidth = ctx.canvas.width / 2;const centerHeight = ctx.canvas.height / 2;/** 起始位置 */let startAngle = 0;// 根据弧度绘制扇形// @ts-ignoreangleList.forEach((item, index) => {// 上一次绘制的结束弧度等于当前次的起始弧度const endAngle = startAngle + item;ctx.beginPath();ctx.moveTo(centerWidth, centerHeight);ctx.arc(centerWidth, centerHeight, 120, startAngle, endAngle);ctx.fillStyle = colorArr[index];ctx.fill();// 记录当前的结束位置作为下一次的起始位置startAngle = endAngle;});}
}
2.绘制两张图片并下载
const downloadImg = (item: ICanvasProp) => {const {posterItemWidth,posterItemHeight,posterBgWidth,posterBgHeight,codeX,codeY,posterCodeBgWidth,posterCodeBgHeight,} = item;// 用canvas绘图,然后再下载const imgName = moment().format('YYYY-MM-DD HH:mm:SS');const canvas = document.createElement('canvas');const ctx = canvas.getContext('2d');canvas.width = posterItemWidth;canvas.height = posterItemHeight;if (ctx) {ctx.rect(0, 0, posterItemWidth, posterItemHeight);const bgImg = new Image();// 解决缓存导致跨域问题bgImg.src = item.bgImgUrl + `?tamp=${new Date().getTime()}`;bgImg.setAttribute('crossOrigin', 'anonymous');bgImg.onload = () => {ctx.drawImage(bgImg, 0, 0, posterBgWidth, posterBgHeight);const codeImg = new Image();// 解决缓存导致跨域问题codeImg.src = item.codeImgUrl + `?tamp=${new Date().getTime()}`;codeImg.setAttribute('crossOrigin', 'anonymous');codeImg.onload = () => {ctx.drawImage(codeImg, codeX, codeY, posterCodeBgWidth, posterCodeBgHeight);const link = document.createElement('a');link.setAttribute('download', `图片-${imgName}.png`);link.setAttribute('href', canvas.toDataURL('image/png'));link.style.display = 'none';document.body.appendChild(link);link.click();document.body.removeChild(link);};};}
}