在小程序常常会用到海报,这就需要canvas的一些常用方法,修饰文字,画图片圆角的封装方法,把它抽成canvas.js文件,方便以后用

  在canvas.js   (笔记---canvas)

    

 1 /**
 2  * 文本换行
 3  * @param {Object} obj
 4  */
 5 export const textWrap = function(obj){
 6   let tr = getTextLine(obj);
 7   for (let i = 0; i < tr.length; i++) {
 8     if (i < obj.line){
 9       let txt = {
10         context: obj.context,
11         x: obj.x,
12         y: obj.y + (i * obj.height),
13         color: obj.color,
14         size: obj.size,
15         align: obj.align,
16         baseline: obj.baseline,
17         text: tr[i],
18         bold: obj.bold
19       };
20       if (i == obj.line - 1) {
21         if (tr.length > obj.line) {
22           txt.text = txt.text.substring(0, txt.text.length - 1) + '...';
23         }
24       }
25       drawText(txt);
26     }
27   }
28 }
29 /**
30  * 渲染文字
31  *
32  * @param {Object} obj
33  */
34 var drawText = function (obj) {
35   obj.context.save();
36   obj.context.setFillStyle(obj.color);
37   obj.context.setFontSize(obj.size);
38   obj.context.setTextAlign(obj.align);
39   obj.context.setTextBaseline(obj.baseline);
40   if (obj.bold) {
41     obj.context.fillText(obj.text, obj.x, obj.y - 0.5);
42     obj.context.fillText(obj.text, obj.x - 0.5, obj.y);
43   }
44   obj.context.fillText(obj.text, obj.x, obj.y);
45   if (obj.bold) {
46     obj.context.fillText(obj.text, obj.x, obj.y + 0.5);
47     obj.context.fillText(obj.text, obj.x + 0.5, obj.y);
48   }
49   obj.context.restore();
50 }
51 /**
52  * 获取文本折行
53  * @param {Object} obj
54  * @return {Array} arrTr
55  */
56 var getTextLine = function(obj){
57   obj.context.setFontSize(obj.size);
58   let arrText = obj.text.split('');
59   console.log(arrText);
60   let line = '';
61   let arrTr = [];
62   for (let i = 0; i < arrText.length; i++) {
63     var testLine = line + arrText[i];
64     var metrics = obj.context.measureText(testLine);
65     var width = metrics.width;
66     if ((width > obj.width && i > 0)||arrText[i]=='\n') {  //
67       arrTr.push(line);
68       line = arrText[i]=='\n'?arrText[i+1]:arrText[i];
69     } else {
70       line = testLine;
71     }
72     if (i == arrText.length - 1) {
73       arrTr.push(line);
74     }
75   }
76   return arrTr;
77 }
78 
79 /**
80  * 圆形头像
81  */
82 export const circleImg = function(context, img, x, y, r){
83   context.save();
84   var d = 2 * r;
85   var cx = x + r;
86   var cy = y + r;
87   context.beginPath();
88   context.arc(cx, cy, r, 0, 2 * Math.PI);
89   context.clip();
90   context.drawImage(img, x, y, d, d);
91   context.restore()
92 }

猜你喜欢

转载自www.cnblogs.com/PinkYun/p/11821226.html