UNPKG

zk-draw

Version:

canvas绘制AI数据的一个工具类

113 lines (105 loc) 3.41 kB
/* * @description 绘制骨架的函数 * @Author: wangfpp * @Date: 2020-04-28 11:44:08 * @Last Modified by: wangfpp * @Last Modified time: 2020-04-28 14:17:14 */ import { copyCtxConf, deepFlatten } from "../../comm/comm"; import { drawArc } from "../draw_cicle/draw_cicle"; import { drawLine } from "../draw_line/draw_line"; import { colorRgb } from "../../comm/comm"; String.prototype.colorRgb = colorRgb; /** * @description 绘制骨架 * @param {Canvas 2D} ctx * @param {Array} pose 骨架的肢体点数据 * @param {Object} option 配置文件 */ const drawStone = (ctx, pose, option) => { const ctxConfig = copyCtxConf(ctx); const defaultConfig = { xkp: 1, ykp: 1, conn_bone :[ //[0, 1], [1, 2], [1, 5], [2, 3], [3, 4], [5, 6], [6, 7], [1, 8], [1, 11], [8, 9], [9, 10], [11, 12], [12, 13] ] }; let reactConfig = Object.assign(ctxConfig, defaultConfig, option), { strokeStyle, fillStyle, lineWidth, lineJoin, lineCap, xkp, ykp, conn_bone } = reactConfig, index = []; if (pose.length > 0) { pose.forEach((piont, i) => { // 骨架绘制 if (piont.every(a => a === 0)) { index.push(i); }; }); let line = filterArray(conn_bone, index, pose)[0]; line.forEach(item => { var start = [item[0][0] * xkp, item[0][1] * ykp]; var end = [item[1][0] * xkp, item[1][1] * ykp]; drawDoubleArc(ctx, start, reactConfig); drawDoubleLine(ctx, start, end, reactConfig); drawDoubleArc(ctx, end, reactConfig); }); } } /** * @description 绘制两个同心圆 * @param {Canvas 2D} ctx * @param {Array} start 圆心 * @param {Object} option 配置参数 */ const drawDoubleArc = (ctx, start, option) => { let { fillStyle } = option; drawArc(ctx, start, 10, { fillStyle: 'rgba(255, 255, 255, 0.4)'}); drawArc(ctx, start, 6, { fillStyle: fillStyle.colorRgb(0.8)}); } /** * @description 绘制双实线 * @param {Canvas} ctx * @param {Array} start 起点 * @param {Array} end 终点 * @param {Object} option */ const drawDoubleLine = (ctx, start, end, option) => { let { lineCap, lineJoin, strokeStyle } = option drawLine(ctx, start, end, { lineCap, lineJoin, strokeStyle: 'rgba(255, 255, 255, 0.4)', lineWidth: 5}); drawLine(ctx, start, end, { lineCap, lineJoin, strokeStyle: strokeStyle.colorRgb(0.8), lineWidth: 2}); } /** * * @param {Array} arr 骨架的链接顺序 * @param {Array} filter 需要过滤的骨架点 * @param {Array} oringial 骨架的数据 */ const filterArray = (arr, filter, oringial) => { let lineData = []; let x = 0, y = 0; let lineIndex = arr.filter(item => { return !(filter.includes(item[0]) || filter.includes(item[1])) }); let singalIndex = Array.from(new Set(deepFlatten(lineIndex))); lineIndex.forEach(item => { lineData.push([oringial[item[0]], oringial[item[1]]]) }); singalIndex.forEach((item, index) => { x += oringial[item][0]; index == 0 ? y = oringial[item][1] : y = Math.min(y, oringial[item][1]); }); return [lineData, x / singalIndex.length, y]; } export { drawStone };