Poster.vue 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. <template>
  2. <view class="canvas">
  3. <canvas canvas-id="myCanvas" :style="{width: width+'px',height: height+'px'}"></canvas>
  4. </view>
  5. </template>
  6. <!--
  7. list参数说明:
  8. 图片渲染:
  9. type: 'image',
  10. x: X轴位置,
  11. y: Y轴位置,
  12. path: 图片路径,
  13. width: 图片宽度,
  14. height: 图片高度,
  15. rotate: 旋转角度
  16. shape: 形状,默认无,可选值:circle 圆形
  17. area: {x,y,width,height} // 绘制范围,超出该范围会被剪裁掉 该属性与shape暂时无法同时使用,area存在时,shape失效
  18. 文字渲染:
  19. type: 'text',
  20. x: X轴位置,
  21. y: Y轴位置,
  22. text: 文本内容,
  23. size: 字体大小,
  24. textBaseline: 基线 默认top 可选值:'top'、'bottom'、'middle'、'normal'
  25. color: 颜色
  26. 多行文字渲染:
  27. type: 'textarea',
  28. x: X轴位置,
  29. y: Y轴位置,
  30. width:换行的宽度
  31. height: 高度,溢出会展示“...”
  32. lineSpace: 行间距
  33. text: 文本内容,
  34. size: 字体大小,
  35. textBaseline: 基线 默认top 可选值:'top'、'bottom'、'middle'、'normal'
  36. color: 颜色
  37. -->
  38. <script>
  39. export default {
  40. name: "Poster",
  41. props: {
  42. // 绘制队列
  43. data: {
  44. type: Object,
  45. required: true
  46. },
  47. width: {
  48. type: Number,
  49. required: true
  50. },
  51. height: {
  52. type: Number,
  53. required: true
  54. },
  55. clicknum:{
  56. type: Number,
  57. default: 0
  58. },
  59. backgroundColor: {
  60. type: String,
  61. default: 'rgba(0,0,0,0)'
  62. }
  63. },
  64. emit: ['on-success', 'on-error'],
  65. data() {
  66. return {
  67. posterUrl: '',
  68. ctx: null, //画布上下文
  69. counter: -1, //计数器
  70. drawPathQueue: [], //画图路径队列
  71. };
  72. },
  73. watch: {
  74. data:{
  75. handler(newVal, oldVal){
  76. console.log(newVal,11111)
  77. this.list = newVal.list
  78. if(this.list.length!=0){
  79. this.generateImg()
  80. console.log('mounted')
  81. }
  82. },
  83. },
  84. drawPathQueue(newVal, oldVal) {
  85. console.log(this.ctx,111111)
  86. // 绘制单行文字
  87. const fillText = (textOptions) => {
  88. console.log(textOptions)
  89. this.ctx.setFillStyle(textOptions.color)
  90. this.ctx.setFontSize(textOptions.size)
  91. this.ctx.setTextBaseline(textOptions.textBaseline || 'top')
  92. this.ctx.fillText(textOptions.text, textOptions.x, textOptions.y)
  93. }
  94. // 绘制段落
  95. const fillParagraph = (textOptions) => {
  96. this.ctx.setFontSize(textOptions.size)
  97. let tempOptions = JSON.parse(JSON.stringify(textOptions));
  98. // 如果没有指定行间距则设置默认值
  99. tempOptions.lineSpace = tempOptions.lineSpace ? tempOptions.lineSpace : 10;
  100. // 获取字符串
  101. let str = textOptions.text;
  102. console.log()
  103. // 计算指定高度可以输出的最大行数
  104. // let lineCount = Math.floor((tempOptions.height + tempOptions.lineSpace) / (tempOptions.size +
  105. // tempOptions.lineSpace))
  106. // 初始化单行宽度
  107. let lineWidth = 0;
  108. let lastSubStrIndex = 0; //每次开始截取的字符串的索引
  109. // 构建一个打印数组
  110. let strArr = str.split("");
  111. let drawArr = [];
  112. let text = "";
  113. while (strArr.length) {
  114. let word = strArr.shift()
  115. text += word;
  116. let textWidth = this.ctx.measureText(text).width;
  117. if (textWidth > textOptions.width) {
  118. // 因为超出宽度 所以要截取掉最后一个字符
  119. text = text.substr(0, text.length - 1)
  120. drawArr.push(text)
  121. text = "";
  122. // 最后一个字还给strArr
  123. strArr.unshift(word)
  124. } else if (!strArr.length) {
  125. drawArr.push(text)
  126. }
  127. }
  128. if (drawArr.length > tempOptions.lineSpace) {
  129. // 超出最大行数
  130. drawArr.length = tempOptions.lineSpace;
  131. let pointWidth = this.ctx.measureText('...').width;
  132. let wordWidth = 0;
  133. let wordArr = drawArr[drawArr.length - 1].split("");
  134. let words = '';
  135. while (pointWidth > wordWidth) {
  136. words += wordArr.pop();
  137. wordWidth = this.ctx.measureText(words).width
  138. }
  139. drawArr[drawArr.length - 1] = wordArr.join('') + '...';
  140. }
  141. // 打印
  142. for (let i = 0; i < drawArr.length; i++) {
  143. tempOptions.y = tempOptions.y + tempOptions.size * i + tempOptions.lineSpace * i; // y的位置
  144. tempOptions.text = drawArr[i]; // 绘制的文本
  145. fillText(tempOptions)
  146. }
  147. }
  148. // 绘制背景
  149. this.ctx.setFillStyle(this.backgroundColor);
  150. this.ctx.fillRect(0, 0, this.width, this.height);
  151. /* 所有元素入队则开始绘制 */
  152. if (newVal.length === this.list.length) {
  153. try {
  154. console.log(this.list,1111111)
  155. // console.log('生成的队列:' + JSON.stringify(newVal));
  156. console.log('开始绘制...')
  157. for (let i = 0; i < this.drawPathQueue.length; i++) {
  158. for (let j = 0; j < this.drawPathQueue.length; j++) {
  159. let current = this.drawPathQueue[j]
  160. /* 按顺序绘制 */
  161. if (current.index === i) {
  162. /* 文本绘制 */
  163. if (current.type === 'text') {
  164. console.log('绘制文本:' + current.text);
  165. fillText(current)
  166. this.counter--
  167. }
  168. /* 多行文本 */
  169. if (current.type === 'textarea') {
  170. console.log('绘制段落:' + current.text);
  171. fillParagraph(current)
  172. this.counter--
  173. }
  174. /* 图片绘制 */
  175. if (current.type === 'image') {
  176. console.log('绘制图片:' + current.path);
  177. console.log(current.area)
  178. if (current.area) {
  179. // 绘制绘图区域
  180. this.ctx.save()
  181. this.ctx.beginPath(); //开始绘制
  182. this.ctx.rect(current.area.x, current.area.y, current.area.width, current.area
  183. .height)
  184. this.ctx.clip();
  185. // 设置旋转中心
  186. let offsetX = current.x + Number(current.width) / 2;
  187. let offsetY = current.y + Number(current.height) / 2;
  188. this.ctx.translate(offsetX, offsetY)
  189. let degrees = current.rotate ? Number(current.rotate) % 360 : 0;
  190. this.ctx.rotate(degrees * Math.PI / 180)
  191. this.ctx.drawImage(current.path, current.x - offsetX, current.y - offsetY,
  192. current.width, current.height)
  193. this.ctx.closePath();
  194. this.ctx.restore(); // 恢复之前保存的上下文
  195. } else if (current.shape == 'circle') {
  196. this.ctx.save(); // 保存上下文,绘制后恢复
  197. this.ctx.beginPath(); //开始绘制
  198. //先画个圆 前两个参数确定了圆心 (x,y) 坐标 第三个参数是圆的半径 四参数是绘图方向 默认是false,即顺时针
  199. let width = (current.width / 2 + current.x);
  200. let height = (current.height / 2 + current.y);
  201. let r = current.width / 2;
  202. this.ctx.arc(width, height, r, 0, Math.PI * 2);
  203. //画好了圆 剪切 原始画布中剪切任意形状和尺寸。一旦剪切了某个区域,则所有之后的绘图都会被限制在被剪切的区域内 这也是我们要save上下文的原因
  204. this.ctx.clip();
  205. // 设置旋转中心
  206. let offsetX = current.x + Number(current.width) / 2;
  207. let offsetY = current.y + Number(current.height) / 2;
  208. this.ctx.translate(offsetX, offsetY)
  209. let degrees = current.rotate ? Number(current.rotate) % 360 : 0;
  210. this.ctx.rotate(degrees * Math.PI / 180)
  211. this.ctx.drawImage(current.path, current.x - offsetX, current.y - offsetY,
  212. current.width, current.height)
  213. this.ctx.closePath();
  214. this.ctx.restore(); // 恢复之前保存的上下文
  215. } else {
  216. console.log(3333,current)
  217. this.ctx.drawImage(current.path, current.x, current.y, current.width, current
  218. .height)
  219. }
  220. this.counter--
  221. }
  222. }
  223. }
  224. }
  225. } catch (err) {
  226. console.log(err)
  227. this.$emit('on-error', err)
  228. }
  229. }
  230. },
  231. counter(newVal, oldVal) {
  232. console.log(newVal)
  233. if (newVal === 0) {
  234. this.ctx.draw()
  235. /* draw完不能立刻转存,需要等待一段时间 */
  236. setTimeout(() => {
  237. console.log('final counter', this.counter);
  238. uni.canvasToTempFilePath({
  239. canvasId: 'myCanvas',
  240. success: (res) => {
  241. console.log('in canvasToTempFilePath');
  242. // 在H5平台下,tempFilePath 为 base64
  243. // console.log('图片已保存至本地:', res.tempFilePath)
  244. this.posterUrl = res.tempFilePath;
  245. this.$emit('on-success', res.tempFilePath)
  246. },
  247. fail: (res) => {
  248. console.log(res)
  249. }
  250. }, this)
  251. }, 1000)
  252. }
  253. }
  254. },
  255. mounted() {
  256. this.ctx = uni.createCanvasContext('myCanvas', this)
  257. },
  258. methods: {
  259. create() {
  260. this.generateImg()
  261. },
  262. /**
  263. * 图片圆角设置
  264. * @param string x x轴位置
  265. * @param string y y轴位置
  266. * @param string w 图片宽
  267. * @param string y 图片高
  268. * @param string r 圆角值
  269. */
  270. generateImg() {
  271. console.log('generateimg',this.drawPathQueue)
  272. this.counter = this.list.length
  273. this.drawPathQueue = []
  274. /* 将图片路径取出放入绘图队列 */
  275. for (let i = 0; i < this.list.length; i++) {
  276. let current = this.list[i]
  277. console.log(this.list[i])
  278. current.index = i
  279. /* 如果是文本直接放入队列 */
  280. if (current.type === 'text' || current.type === 'textarea' || current.type === 'image' && current.use !== 'bg' ) {
  281. this.drawPathQueue.push(current)
  282. continue
  283. }
  284. if( current.use === 'head'&&current.imageType === 'wl'){
  285. this.drawPathQueue.push(current)
  286. continue
  287. }
  288. /* 图片需获取本地缓存path放入队列 */
  289. uni.getImageInfo({
  290. src: current.path,
  291. success: (res) => {
  292. current.path = res.path
  293. this.drawPathQueue.push(current)
  294. }
  295. })
  296. }
  297. },
  298. saveImg() {
  299. uni.canvasToTempFilePath({
  300. canvasId: 'myCanvas',
  301. success: (res) => {
  302. // 在H5平台下,tempFilePath 为 base64
  303. uni.saveImageToPhotosAlbum({
  304. filePath: res.tempFilePath,
  305. success: () => {
  306. console.log('save success');
  307. }
  308. });
  309. }
  310. })
  311. }
  312. }
  313. }
  314. </script>
  315. <style lang="scss" scoped>
  316. .canvas {
  317. position: fixed;
  318. top: 100rpx;
  319. left: 750rpx;
  320. }
  321. </style>