mp-painter
Advanced tools
Comparing version 0.2.13 to 1.0.0-beta.1
@@ -1,3 +0,3 @@ | ||
/// <reference types="uni-app" /> | ||
import Painter from "./painter"; | ||
import { PainterContext } from "./painter-context/index"; | ||
interface ILineSpliterContextOption { | ||
@@ -14,3 +14,3 @@ fontSize: number; | ||
width: number; | ||
ctx: CanvasContext; | ||
ctx: PainterContext; | ||
painter: Painter; | ||
@@ -17,0 +17,0 @@ content: string; |
@@ -18,3 +18,3 @@ import Painter from "../painter"; | ||
* - contain 等比缩放,使图片刚好能完整显示出来 | ||
* - cover 等比缩放,使图片更好能占满容器 | ||
* - cover 等比缩放,使图片刚好能占满容器 | ||
*/ | ||
@@ -21,0 +21,0 @@ objectFit?: ObjectFit; |
/// <reference types="uni-app" /> | ||
import { UniPlatforms } from "../utils/platform"; | ||
import { BuiltInPainterElementOption } from "./painter-element/index"; | ||
import { FillStrokeStyle } from "./value"; | ||
import { PainterContext } from "./painter-context/index"; | ||
interface IPanterOption { | ||
platform?: UniPlatforms; | ||
upx2px?: (upx: number) => number; | ||
platform?: UniPlatforms; | ||
} | ||
/** 单次绘制选项 */ | ||
interface IDrawOption { | ||
} | ||
export default class Painter { | ||
ctx: CanvasContext; | ||
upx2px: (upx: number) => number; | ||
platform: UniPlatforms; | ||
ctx: PainterContext; | ||
upx2px: NonNullable<IPanterOption["upx2px"]>; | ||
platform: NonNullable<IPanterOption["platform"]>; | ||
constructor(ctx: CanvasContext, { platform, upx2px }?: IPanterOption); | ||
draw(element: BuiltInPainterElementOption): Promise<import("./value").Size>; | ||
_drawObj(paintObj: BuiltInPainterElementOption): Promise<import("./value").Size>; | ||
/** | ||
* 兼容设置填充样式 | ||
*/ | ||
setFillStyle(color: FillStrokeStyle): void; | ||
/** | ||
* 兼容设置描边样式 | ||
*/ | ||
setStrokeStyle(color: FillStrokeStyle): void; | ||
/** 测量文本宽度 */ | ||
measureText(text: string, fontSize: number): number; | ||
/** 兼容地,根据控制点和半径绘制圆弧路径 */ | ||
arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void; | ||
/** 兼容绘制图片 */ | ||
drawImage(imageResource: string, sx: number, sy: number, sWidth: number, sHeigt: number, dx: number, dy: number, dWidth: number, dHeight: number): any; | ||
draw(elementOption: BuiltInPainterElementOption, drawOption?: IDrawOption): Promise<import("./value").Size>; | ||
/** 创建元素对象 */ | ||
createElement(elementOption: BuiltInPainterElementOption): import("./painter-element/element-text").PainterTextElement | import("./painter-element/element-text-block").PainterTextBlockElement | import("./painter-element/element-image").PainterImageElement | import("./painter-element/element-line").PainterLineElement | import("./painter-element/element-rect").PainterRectagleElement | import("./painter-element/element-container").PainterContainerElement | import("./painter-element/element-clip").PainterClipElement | import("./painter-element/element-transform").PainterTransformElement; | ||
/** 获取指定元素的尺寸 */ | ||
layout(elementOption: BuiltInPainterElementOption): Promise<import("./value").Size>; | ||
} | ||
export {}; |
@@ -1,1 +0,1 @@ | ||
module.exports=function(t){var i={};function e(n){if(i[n])return i[n].exports;var o=i[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,e),o.l=!0,o.exports}return e.m=t,e.c=i,e.d=function(t,i,n){e.o(t,i)||Object.defineProperty(t,i,{enumerable:!0,get:n})},e.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},e.t=function(t,i){if(1&i&&(t=e(t)),8&i)return t;if(4&i&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(e.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&i&&"string"!=typeof t)for(var o in t)e.d(n,o,function(i){return t[i]}.bind(null,o));return n},e.n=function(t){var i=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(i,"a",i),i},e.o=function(t,i){return Object.prototype.hasOwnProperty.call(t,i)},e.p="",e(e.s=0)}([function(t,i,e){"use strict";e.r(i);const n="object"==typeof swan?"mp-baidu":"object"==typeof my?"mp-alipay":"mp-weixin",o=function(){if("undefined"!=typeof uni)return uni;if("undefined"!=typeof wx)return wx;throw new Error("enviroment not support")}(),r=[.296,.313,.436,.638,.586,.89,.87,.256,.334,.334,.455,.742,.241,.433,.241,.427,.586,.586,.586,.586,.586,.586,.586,.586,.586,.586,.241,.241,.742,.742,.742,.483,1.031,.704,.627,.669,.762,.55,.531,.744,.773,.294,.396,.635,.513,.977,.813,.815,.612,.815,.653,.577,.573,.747,.676,1.018,.645,.604,.62,.334,.416,.334,.742,.448,.295,.553,.639,.501,.64,.567,.347,.64,.616,.266,.267,.544,.266,.937,.616,.636,.639,.64,.382,.463,.373,.616,.525,.79,.507,.529,.492,.334,.269,.334,.742,.296];var s=function(t,i,e,n){return new(e||(e=Promise))((function(o,r){function s(t){try{l(n.next(t))}catch(t){r(t)}}function h(t){try{l(n.throw(t))}catch(t){r(t)}}function l(t){var i;t.done?o(t.value):(i=t.value,i instanceof e?i:new e((function(t){t(i)}))).then(s,h)}l((n=n.apply(t,i||[])).next())}))};class h{constructor(t,i,e){var n,o,r;this.offsetTop=0,this.offsetLeft=0,this.contentHeight=0,this.contentWidth=0,this.painter=t,this.parent=e,this.position=null!=(n=i.position)?n:"static",this.left=null!=(o=i.left)?o:0,this.top=null!=(r=i.top)?r:0}layout(){return s(this,void 0,void 0,(function*(){let t=yield this._layout();return this.contentHeight=t.height,this.contentWidth=t.width,t}))}get anchorX(){var t,i;return null!=(i=null===(t=this.parent)||void 0===t?void 0:t.elementX)?i:0}get anchorY(){var t,i;return null!=(i=null===(t=this.parent)||void 0===t?void 0:t.elementY)?i:0}get elementX(){switch(this.position){case"absolute":return this.left+this.anchorX;case"static":return this.left+this.offsetLeft+this.anchorX;default:throw new TypeError("unknown position type")}}get elementY(){switch(this.position){case"absolute":return this.top+this.anchorY;case"static":return this.top+this.offsetTop+this.anchorY;default:throw new TypeError("unknown position type")}}get offsetHeight(){return this.top+this.contentHeight}get offsetWidth(){return this.left+this.contentWidth}}class l extends class{constructor(t){this.element=t}get painter(){return this.element.painter}}{constructor(t,i){super(t),this.option=i}get style(){const{ctx:t,upx2px:i}=this.painter,{x1:e,x2:n,y1:o,y2:r}=this.option,s=t.createLinearGradient(i(this.element.elementX+e),i(this.element.elementY+o),i(this.element.elementX+n),i(this.element.elementY+r));return this.option.colorStops.forEach(t=>{s.addColorStop(t.offset,t.color)}),s}}function a(t,i){if("string"==typeof i)return i;switch(i.type){case"liner-gradient":return new l(t,i).style;default:throw new Error("Unkwon option type")}}function c(t,i,e=1){return e%2?[Math.floor(t)+.5,Math.floor(i)+.5]:[Math.round(t),Math.round(i)]}class u extends h{constructor(t,i,e){var n,o,r,s,h;super(t,i,e),this.option={dx:(n=i.dx,null!=n?n:0),dy:(o=i.dy,null!=o?o:0),color:(r=i.color,null!=r?r:"#000"),dashPattern:(s=i.dashPattern,null!=s?s:[1,0]),lineWidth:(h=i.lineWidth,null!=h?h:1)}}_layout(){return{width:this.option.dx,height:this.option.dy}}paint(){let t=this.painter.upx2px(this.elementX),i=this.painter.upx2px(this.elementY),e=this.painter.upx2px(this.elementX+this.option.dx),n=this.painter.upx2px(this.elementY+this.option.dy),o=this.painter.upx2px(this.option.lineWidth);this.painter.ctx.beginPath(),this.painter.ctx.moveTo(...c(t,i,o)),this.painter.ctx.lineTo(...c(e,n,o)),this.painter.ctx.setLineDash(this.option.dashPattern.map(t=>this.painter.upx2px(t))),this.painter.setStrokeStyle(a(this,this.option.color)),this.painter.ctx.lineWidth=o,this.painter.ctx.stroke()}}function p(t){return t.replace(/[\n\r]/g,"")}class d extends h{constructor(t,i,e){var n,o,r,s,h,l,a,c,u,d;super(t,i,e),this.option={color:(n=i.color,null!=n?n:"#000"),align:(o=i.align,null!=o?o:"left"),fontWeight:(r=i.fontWeight,null!=r?r:"normal"),fontStyle:(s=i.fontStyle,null!=s?s:"normal"),fontFamily:(h=i.fontFamily,null!=h?h:"serial"),fontSize:(l=i.fontSize,null!=l?l:30),baseline:(a=i.baseline,null!=a?a:"top"),content:(c=i.content,null!=c?c:""),width:(u=i.width,null!=u?u:void 0),textDecoration:(d=i.textDecoration,null!=d?d:"none")},this.option.content=p(this.option.content)}_layout(){var t;return{width:null!=(t=this.option.width)?t:this.painter.measureText(this.option.content,this.option.fontSize),height:this.option.fontSize}}paint({inTextBlock:t=!1}={}){this.painter.ctx.font=["normal"!=this.option.fontWeight&&this.option.fontWeight,"normal"!=this.option.fontStyle&&this.option.fontStyle,this.painter.upx2px(this.option.fontSize)+"px",this.option.fontFamily].filter(Boolean).join(" "),t||this.painter.setFillStyle(a(this,this.option.color)),this.painter.ctx.setFontSize(this.painter.upx2px(this.option.fontSize)),this.painter.ctx.setTextBaseline(this.option.baseline),this.painter.ctx.setTextAlign(this.option.align),console.debug("mp-painter:fillText:",this.option.content,"x=",this.elementX,"y=",this.elementY),this.painter.ctx.fillText(this.option.content,this.painter.upx2px(this.elementX),this.painter.upx2px(this.elementY)),this.paintTextDecoration()}paintTextDecoration(){"line-through"==this.option.textDecoration&&new u(this.painter,{top:this.elementY+.4*this.option.fontSize,left:this.elementX,dx:this.contentWidth,dy:0,color:this.option.color}).paint()}}class f{constructor(t){this.fontSize=t.fontSize,this.lineClamp=t.lineClamp||1/0,this.width=t.width,this.ctx=t.painter.ctx,this.painter=t.painter,this.content=t.content,this.lines=[],this.currentLineText="",this.position=0,this.endPostion=this.position,this.isOverflow=!1,this.isDry=!1,this.isFull=!1}split(){return this.ctx.setFontSize(this.fontSize),this.fillText(),this.lines}minCharNumberInWidth(t){return Math.ceil(t/this.fontSize)}freeSpaceInCurrentLine(){if(this.currentLineText.length){let t=this.painter.measureText(this.currentLineText,this.fontSize);return this.width-(t||0)}return this.width}adjustCharNumberInCurrentLine(t){let i=this.currentLineText.length+t,e=this.content.length;i=Math.min(i,e),this.isDry=i==e,this.currentLineText=this.content.slice(0,i)}commitLine(){this.content=this.content.slice(this.currentLineText.length),this.lines.push(this.currentLineText),this.currentLineText="",this.lines.length==this.lineClamp&&(this.isFull=!0,0==this.isDry&&(this.isOverflow=!0))}handleOverflow(){let t=this.lines.pop();t=t.substring(0,Math.max(0,t.length-1))+"...",this.lines.push(t)}fillText(){let t=this.freeSpaceInCurrentLine();if(t<=0){if(this.adjustCharNumberInCurrentLine(-1),this.commitLine(),this.isOverflow&&this.handleOverflow(),this.isFull)return;t=this.freeSpaceInCurrentLine()}else if(this.isDry)return void this.commitLine();let i=this.minCharNumberInWidth(t);this.adjustCharNumberInCurrentLine(i),this.fillText()}}var x=function(t,i,e,n){return new(e||(e=Promise))((function(o,r){function s(t){try{l(n.next(t))}catch(t){r(t)}}function h(t){try{l(n.throw(t))}catch(t){r(t)}}function l(t){var i;t.done?o(t.value):(i=t.value,i instanceof e?i:new e((function(t){t(i)}))).then(s,h)}l((n=n.apply(t,i||[])).next())}))};class m extends h{constructor(t,i,e){var n,o,r,s,h,l,a;super(t,i,e),this.option=Object.assign(Object.assign({},i),{width:(n=i.width,null!=n?n:100),height:(o=i.height,null!=o?o:"auto"),fontSize:(r=i.fontSize,null!=r?r:30),content:(s=i.content,null!=s?s:""),lineHeight:(h=i.lineHeight,null!=h?h:40),lineClamp:(l=i.lineClamp,null!=l?l:0),color:(a=i.color,null!=a?a:"black")}),this.lines=[],this.option.content=p(this.option.content)}_layout(){return this.lines=new f({fontSize:this.option.fontSize,lineClamp:this.option.lineClamp,width:this.option.width,painter:this.painter,content:this.option.content}).split(),{width:this.option.width,height:"auto"==this.option.height?(this.lines.length-1)*this.option.lineHeight+this.option.fontSize:this.option.height}}paint(){return x(this,void 0,void 0,(function*(){this.painter.setFillStyle(a(this,this.option.color)),this.lines.map((t,i)=>{let e=Object.assign(Object.assign({},this.option),{type:"text",top:this.elementY+i*this.option.lineHeight,left:this.elementX,position:this.position,content:t});new d(this.painter,e).paint({inTextBlock:!0})})}))}}var w=function(t,i,e,n){return new(e||(e=Promise))((function(o,r){function s(t){try{l(n.next(t))}catch(t){r(t)}}function h(t){try{l(n.throw(t))}catch(t){r(t)}}function l(t){var i;t.done?o(t.value):(i=t.value,i instanceof e?i:new e((function(t){t(i)}))).then(s,h)}l((n=n.apply(t,i||[])).next())}))};const y=function(t){let i=Object.create(null);return function(e){return e in i||(i[e]=t(e)),i[e]}}((function(t){return w(this,void 0,void 0,(function*(){try{let{width:e=100,height:n=100}=yield(i=uni.getImageInfo,function(t={}){return new Promise((e,n)=>{t.success=e,t.fail=n,i(t)})})({src:t});return{width:e,height:n}}catch(t){return console.log("mp-painter:getImageOriginSize: fail, use default size: width = 100, height = 100"),{width:100,height:100}}var i}))}));class g extends h{constructor(t,i,e){var n,o,r,s;super(t,i,e),this.option={width:(n=i.width,null!=n?n:100),height:(o=i.height,null!=o?o:100),objectFit:(r=i.objectFit,null!=r?r:"fill"),objectPosition:(s=i.objectPosition,null!=s?s:["center","center"]),src:i.src}}_layout(){return{width:this.option.width,height:this.option.height}}paint(){return w(this,void 0,void 0,(function*(){let t=this.painter.upx2px;if(!this.option.src)return;let i=yield function(t,i){return w(this,void 0,void 0,(function*(){let e=t.platform;return/^\./.test(i.src)||/^\/static/.test(i.src)||/^data:image\//.test(i.src)||"mp-alipay"==e&&/^https:\/\/resource\//.test(i.src)||"mp-weixin"==e&&/^wxfile:/.test(i.src)||"mp-baidu"==e&&/^bdfile:\/\/tmp/.test(i.src)?i.src:(console.log("mp-painter:绘制图片: 下载图片文件:",i.src),yield(n=i.src,new Promise((t,i)=>o.downloadFile({url:n,success:i=>t(i.tempFilePath),fail:i}))).catch(t=>(console.log("mp-painter:下载错误: ",t),"")));var n}))}(this.painter,this.option);if(i)if(console.log("mp-painter:调用小程序drawImage,使用:",i),"fill"!=this.option.objectFit){let{sx:e,sy:n,sh:o,sw:r,dx:s,dy:h,dh:l,dw:a}=function(t,i,e){var n,o;let r=i.width/i.height,s=e.width/e.height,h=1;if(r>s&&"contain"==t.objectFit||r<=s&&"cover"==t.objectFit)h=e.width/i.width;else{if(!(r>s&&"cover"==t.objectFit||r<=s&&"contain"==t.objectFit))throw new Error("Unkonwn concreteScale");h=e.height/i.height}let l=i.width*h,a=i.height*h,c={left:0,center:.5,right:1}[(null===(n=t.objectPosition)||void 0===n?void 0:n[0])||"center"],u={top:0,center:.5,bottom:1}[(null===(o=t.objectPosition)||void 0===o?void 0:o[1])||"center"],p=(e.width-l)*c,d=(e.height-a)*u,f=(t,i)=>[(t-p)/h,(i-d)/h],[x,m]=f(0,0),[w,y]=f(e.width,e.height);return{sx:Math.max(x,0),sy:Math.max(m,0),sw:Math.min(w-x,i.width),sh:Math.min(y-m,i.height),dx:Math.max(p,0),dy:Math.max(d,0),dw:Math.min(l,e.width),dh:Math.min(a,e.height)}}({objectFit:this.option.objectFit,objectPosition:this.option.objectPosition},yield y(i),{width:this.option.width,height:this.option.height});this.painter.drawImage(i,e,n,r,o,t(s+this.elementX),t(h+this.elementY),t(a),t(l))}else this.painter.ctx.drawImage(i,t(this.elementX),t(this.elementY),t(this.option.width),t(this.option.height))}))}}class v extends class{constructor(t,i){var e,n;this.element=t,this.left=null!=(e=i.left)?e:0,this.top=null!=(n=i.top)?n:0}get painter(){return this.element.painter}get pathX(){return this.element.elementX+this.left}get pathY(){return this.element.elementY+this.top}}{constructor(t,i){super(t,i),this.option=i,this.option.borderRadius&&this.assertBorderRadius()}assertBorderRadius(){this.normalizedBorderRadius.some(t=>t<0)&&(console.warn("border radius must greater than 0, got:",this.normalizedBorderRadius.join(",")),this.option.borderRadius=0)}paint(){this.reduceBorderRadius();let[t,i,e,n]=this.normalizedBorderRadius,{ctx:o,upx2px:r}=this.painter;o.beginPath(),o.moveTo(r(this.pathX),r(this.pathY+t)),this.painter.arcTo(r(this.pathX),r(this.pathY),r(this.pathX+t),r(this.pathY),r(t)),this.painter.arcTo(r(this.pathX+this.option.width),r(this.pathY),r(this.pathX+this.option.width),r(this.pathY+i),r(i)),this.painter.arcTo(r(this.pathX+this.option.width),r(this.pathY+this.option.height),r(this.pathX+this.option.width-e),r(this.pathY+this.option.height),r(e)),this.painter.arcTo(r(this.pathX),r(this.pathY+this.option.height),r(this.pathX),r(this.pathY+this.option.height-n),r(n)),o.closePath()}get normalizedBorderRadius(){return"number"==typeof this.option.borderRadius?Array.from({length:4}).fill(this.option.borderRadius):[...this.option.borderRadius]}reduceBorderRadius(){let[t,i,e,n]=this.normalizedBorderRadius,o=Math.min(this.option.width/(t+i),this.option.height/(i+e),this.option.width/(n+e),this.option.height/(t+n));o>=1||(this.option.borderRadius=this.normalizedBorderRadius.map(t=>t*o))}}function b(t,i){switch(i.type){case"rounded-rect":return new v(t,i);default:throw new Error("Unkwon option type")}}class S extends h{constructor(t,i,e){var n,o,r,s,h,l,a;super(t,i,e),this.option={width:(n=i.width,null!=n?n:100),height:(o=i.height,null!=o?o:100),borderRadius:(r=i.borderRadius,null!=r?r:0),background:(s=i.background,null!=s?s:"transparent"),borderStyle:(h=i.borderStyle,null!=h?h:"solid"),borderWidth:(l=i.borderWidth,null!=l?l:0),borderColor:(a=i.borderColor,null!=a?a:"#000")}}_layout(){return{width:this.option.width,height:this.option.height}}paint(){(this.shouldFill||this.shouldStroke)&&(this.option.borderRadius?this.paintByPath():this.paintByRect())}get shouldFill(){return"trasparent"!==this.option.background}get shouldStroke(){return this.option.borderWidth>0}applyFillStyle(){this.painter.setFillStyle(a(this,this.option.background))}applyStrokeStyle(){var t,i;this.painter.ctx.setLineDash((t=this.option.borderStyle,{dashed:[i=this.option.borderWidth,i],solid:[10,0]}[t])),this.painter.ctx.lineWidth=this.painter.upx2px(this.option.borderWidth),this.painter.setStrokeStyle(this.option.borderColor)}paintByRect(){let t=[this.painter.upx2px(this.elementX),this.painter.upx2px(this.elementY),this.painter.upx2px(this.option.width),this.painter.upx2px(this.option.height)];this.shouldFill&&(this.applyFillStyle(),this.painter.ctx.fillRect(...t)),this.shouldStroke&&(this.applyStrokeStyle(),this.painter.ctx.strokeRect(...t))}paintByPath(){b(this,{type:"rounded-rect",height:this.option.height,width:this.option.width,borderRadius:this.option.borderRadius}).paint(),this.shouldFill&&(this.painter.setFillStyle(a(this,this.option.background)),this.painter.ctx.fill()),this.shouldStroke&&(this.applyStrokeStyle(),this.painter.ctx.stroke())}}var T=function(t,i,e,n){return new(e||(e=Promise))((function(o,r){function s(t){try{l(n.next(t))}catch(t){r(t)}}function h(t){try{l(n.throw(t))}catch(t){r(t)}}function l(t){var i;t.done?o(t.value):(i=t.value,i instanceof e?i:new e((function(t){t(i)}))).then(s,h)}l((n=n.apply(t,i||[])).next())}))};class j extends h{constructor(t,i,e){var n,o,r,s;super(t,i,e),this.childOffsetTop=0,this.childOffsetLeft=0,this.option={direction:(n=i.direction,null!=n?n:"vertical"),width:(o=i.width,null!=o?o:"auto"),height:(r=i.height,null!=r?r:"auto"),children:(s=i.children,null!=s?s:[])},this.children=this.option.children.map(t=>C(this.painter,t,this))}_layout(){return T(this,void 0,void 0,(function*(){return yield this.layoutChildren(),{width:this.calcContainerWidth(),height:this.calcContainerHeight()}}))}layoutChildren(){return T(this,void 0,void 0,(function*(){for(let t of this.children)yield this.layoutChild(t)}))}layoutChild(t){return T(this,void 0,void 0,(function*(){yield t.layout(),"absolute"!=t.position&&("vertical"==this.option.direction?(t.offsetTop=this.childOffsetTop,this.childOffsetTop+=t.offsetHeight):(t.offsetLeft=this.childOffsetLeft,this.childOffsetLeft+=t.offsetWidth))}))}calcContainerWidth(){if("number"==typeof this.option.width)return this.option.width;switch(this.option.direction){case"vertical":return this.childrenMaxWidth();case"horizontal":return this.childOffsetLeft;default:throw new TypeError("Unknown direction")}}calcContainerHeight(){if("number"==typeof this.option.height)return this.option.height;switch(this.option.direction){case"vertical":return this.childOffsetTop;case"horizontal":return this.childrenMaxHeight();default:throw new TypeError("Unknown direction")}}paint(){return T(this,void 0,void 0,(function*(){for(let t of this.children)yield t.paint()}))}childrenMaxWidth(){return Math.max(...this.children.map(t=>t.offsetWidth))}childrenMaxHeight(){return Math.max(...this.children.map(t=>t.offsetHeight))}}var O=function(t,i,e,n){return new(e||(e=Promise))((function(o,r){function s(t){try{l(n.next(t))}catch(t){r(t)}}function h(t){try{l(n.throw(t))}catch(t){r(t)}}function l(t){var i;t.done?o(t.value):(i=t.value,i instanceof e?i:new e((function(t){t(i)}))).then(s,h)}l((n=n.apply(t,i||[])).next())}))};class P extends h{constructor(t,i,e){super(t,i,e),this.contentElement=C(t,i.content,this),this.clipPath=b(this,i.path)}_layout(){return this.contentElement.layout()}paint(){return O(this,void 0,void 0,(function*(){this.painter.ctx.save(),yield this.clipPath.paint(),this.painter.ctx.clip(),yield this.contentElement.paint(),this.painter.ctx.restore()}))}}var k=function(t,i,e,n){return new(e||(e=Promise))((function(o,r){function s(t){try{l(n.next(t))}catch(t){r(t)}}function h(t){try{l(n.throw(t))}catch(t){r(t)}}function l(t){var i;t.done?o(t.value):(i=t.value,i instanceof e?i:new e((function(t){t(i)}))).then(s,h)}l((n=n.apply(t,i||[])).next())}))};class F extends h{constructor(t,i,e){var n,o;super(t,i,e),this.contentElement=C(t,i.content,this),this.transformOptions=null!=(n=i.transform)?n:[],this.transformOrigin=null!=(o=i.transformOrigin)?o:["center","center"]}_layout(){return this.contentElement.layout()}paint(){return k(this,void 0,void 0,(function*(){this.painter.ctx.save(),this.withTransformOrigin(()=>this.transform()),yield this.contentElement.paint(),this.painter.ctx.restore()}))}transform(){this.transformOptions.forEach(t=>this.singleTransform(t))}singleTransform(t){var i,e,n,o;switch(t.type){case"translate":return this.painter.ctx.translate(this.painter.upx2px(null!=(i=t.x)?i:0),this.painter.upx2px(null!=(e=t.y)?e:0));case"rotate":return this.painter.ctx.rotate(t.rotate/180*Math.PI);case"scale":return this.painter.ctx.scale(null!=(n=t.scaleWidth)?n:1,null!=(o=t.scaleHeight)?o:1);case"set-matrix":return this.painter.ctx.setTransform(t.scaleX,t.skewX,t.skewY,t.scaleY,this.painter.upx2px(t.translateX),this.painter.upx2px(t.translateY));default:throw new Error("Unknown transform type.")}}withTransformOrigin(t){const i={x:this.elementX+this.contentWidth*{left:0,center:.5,right:1}[this.transformOrigin[0]],y:this.elementY+this.contentHeight*{top:0,center:.5,bottom:1}[this.transformOrigin[1]]};this.singleTransform({type:"translate",x:i.x,y:i.y}),t(),this.singleTransform({type:"translate",x:-i.x,y:-i.y})}}function C(t,i,e){switch(i.type){case"text":return new d(t,i,e);case"text-block":return new m(t,i,e);case"image":return new g(t,i,e);case"line":return new u(t,i,e);case"rect":return new S(t,i,e);case"container":return new j(t,i,e);case"clip":return new P(t,i,e);case"transform":return new F(t,i,e);default:throw new TypeError("Unkown painter element type")}}let X=function(){var t;if("function"==typeof o.upx2px)return o.upx2px;let i=(null!=(t=o.getSystemInfoSync().screenWidth)?t:375)/750;return function(t){return t*i}}();e.d(i,"default",(function(){return z}));var Y=function(t,i,e,n){return new(e||(e=Promise))((function(o,r){function s(t){try{l(n.next(t))}catch(t){r(t)}}function h(t){try{l(n.throw(t))}catch(t){r(t)}}function l(t){var i;t.done?o(t.value):(i=t.value,i instanceof e?i:new e((function(t){t(i)}))).then(s,h)}l((n=n.apply(t,i||[])).next())}))};class z{constructor(t,{platform:i=n,upx2px:e}={}){this.ctx=t,this.platform=i,this.upx2px=null!=e?e:X,"mp-alipay"==i&&(this.upx2px=t=>(null!=e?e:X)(2*t))}draw(t){return Y(this,void 0,void 0,(function*(){let i=yield this._drawObj(t);return yield new Promise(t=>this.ctx.draw(!0,t)),yield function(t=0){return new Promise(i=>setTimeout(i,t))}(100),i}))}_drawObj(t){return Y(this,void 0,void 0,(function*(){let i=C(this,t),e=yield i.layout();return yield i.paint(),e}))}setFillStyle(t){"mp-baidu"==this.platform?this.ctx.setFillStyle(t):this.ctx.fillStyle=t}setStrokeStyle(t){"mp-baidu"==this.platform?this.ctx.setStrokeStyle(t):this.ctx.strokeStyle=t}measureText(t,i){if("mp-weixin"==this.platform&&(t.includes("\n")||t.includes("\r"))&&console.warn(`mp-painter:measureText:字符串 "${t}" 中包含换行符,结果在 iPhone 上可能不准确`),"mp-baidu"==this.platform){let e=this.ctx.measureText(t).width;if(e)return e/10*i}else{if("mp-alipay"==this.platform)return t.split("").reduce((t,i)=>{let e=i.charCodeAt(0);return t+(r[e-32]||1)},0)*i;{this.ctx.setFontSize(i);let e=this.ctx.measureText(t).width;if(e)return e}}return t.length*i}arcTo(t,i,e,n,o){return o<2?this.ctx.lineTo(t,i):this.ctx.arcTo(t,i,e,n,o)}drawImage(t,i,e,n,o,r,s,h,l){return 9!=arguments.length?this.ctx.drawImage.call(this,...arguments):"mp-baidu"==this.platform?this.ctx.drawImage(t,r,s,h,l,i,e,n,o):this.ctx.drawImage(t,i,e,n,o,r,s,h,l)}}}]); | ||
module.exports=function(t){var e={};function i(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,i),o.l=!0,o.exports}return i.m=t,i.c=e,i.d=function(t,e,n){i.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},i.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},i.t=function(t,e){if(1&e&&(t=i(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(i.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var o in t)i.d(n,o,function(e){return t[e]}.bind(null,o));return n},i.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return i.d(e,"a",e),e},i.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},i.p="",i(i.s=0)}([function(t,e,i){"use strict";i.r(e);const n="object"==typeof swan?"mp-baidu":"object"==typeof my?"mp-alipay":"object"==typeof wx?"mp-weixin":"object"==typeof window?"h5":"mp-weixin",o=function(){if("undefined"!=typeof uni)return uni;if("undefined"!=typeof wx)return wx;if("undefined"!=typeof window)return{upx2px:t=>t,getSystemInfoSync:()=>({screenWidth:window.innerWidth}),downloadFile:t=>{var e,i;return null===(i=(e=t).success)||void 0===i?void 0:i.call(e,{tempFilePath:t.url})}};throw new Error("enviroment not support")}();var r=function(t,e,i,n){return new(i||(i=Promise))((function(o,r){function s(t){try{a(n.next(t))}catch(t){r(t)}}function h(t){try{a(n.throw(t))}catch(t){r(t)}}function a(t){var e;t.done?o(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(s,h)}a((n=n.apply(t,e||[])).next())}))};class s{constructor(t,e,i){var n,o,r;this.offsetTop=0,this.offsetLeft=0,this.contentHeight=0,this.contentWidth=0,this.painter=t,this.parent=i,this.position=null!=(n=e.position)?n:"static",this.left=null!=(o=e.left)?o:0,this.top=null!=(r=e.top)?r:0}layout(){return r(this,void 0,void 0,(function*(){let t=yield this._layout();return this.contentHeight=t.height,this.contentWidth=t.width,t}))}get anchorX(){var t,e;return null!=(e=null===(t=this.parent)||void 0===t?void 0:t.elementX)?e:0}get anchorY(){var t,e;return null!=(e=null===(t=this.parent)||void 0===t?void 0:t.elementY)?e:0}get elementX(){switch(this.position){case"absolute":return this.left+this.anchorX;case"static":return this.left+this.offsetLeft+this.anchorX;default:throw new TypeError("unknown position type")}}get elementY(){switch(this.position){case"absolute":return this.top+this.anchorY;case"static":return this.top+this.offsetTop+this.anchorY;default:throw new TypeError("unknown position type")}}get offsetHeight(){return this.top+this.contentHeight}get offsetWidth(){return this.left+this.contentWidth}}class h extends class{constructor(t){this.element=t}get painter(){return this.element.painter}}{constructor(t,e){super(t),this.option=e}get style(){const{ctx:t,upx2px:e}=this.painter,{x1:i,x2:n,y1:o,y2:r}=this.option,s=t.createLinearGradient(e(this.element.elementX+i),e(this.element.elementY+o),e(this.element.elementX+n),e(this.element.elementY+r));return this.option.colorStops.forEach(t=>{s.addColorStop(t.offset,t.color)}),s}}function a(t,e){if("string"==typeof e)return e;switch(e.type){case"liner-gradient":return new h(t,e).style;default:throw new Error("Unkwon option type")}}function l(t,e,i=1){return i%2?[Math.floor(t)+.5,Math.floor(e)+.5]:[Math.round(t),Math.round(e)]}class c extends s{constructor(t,e,i){var n,o,r,s,h;super(t,e,i),this.option={dx:(n=e.dx,null!=n?n:0),dy:(o=e.dy,null!=o?o:0),color:(r=e.color,null!=r?r:"#000"),dashPattern:(s=e.dashPattern,null!=s?s:[1,0]),lineWidth:(h=e.lineWidth,null!=h?h:1)}}_layout(){return{width:this.option.dx,height:this.option.dy}}paint(){let t=this.painter.upx2px(this.elementX),e=this.painter.upx2px(this.elementY),i=this.painter.upx2px(this.elementX+this.option.dx),n=this.painter.upx2px(this.elementY+this.option.dy),o=this.painter.upx2px(this.option.lineWidth);this.painter.ctx.beginPath(),this.painter.ctx.moveTo(...l(t,e,o)),this.painter.ctx.lineTo(...l(i,n,o)),this.painter.ctx.setLineDash(this.option.dashPattern.map(t=>this.painter.upx2px(t))),this.painter.ctx.setStrokeStyle(a(this,this.option.color)),this.painter.ctx.lineWidth=o,this.painter.ctx.stroke()}}function u(t){return t.replace(/[\n\r]/g,"")}class p extends s{constructor(t,e,i){var n,o,r,s,h,a,l,c,p,d;super(t,e,i),this.option={color:(n=e.color,null!=n?n:"#000"),align:(o=e.align,null!=o?o:"left"),fontWeight:(r=e.fontWeight,null!=r?r:"normal"),fontStyle:(s=e.fontStyle,null!=s?s:"normal"),fontFamily:(h=e.fontFamily,null!=h?h:"serial"),fontSize:(a=e.fontSize,null!=a?a:30),baseline:(l=e.baseline,null!=l?l:"top"),content:(c=e.content,null!=c?c:""),width:(p=e.width,null!=p?p:void 0),textDecoration:(d=e.textDecoration,null!=d?d:"none")},this.option.content=u(this.option.content)}_layout(){var t;return{width:null!=(t=this.option.width)?t:this.painter.ctx.measureTextWidth(this.option.content,this.option.fontSize),height:this.option.fontSize}}paint({inTextBlock:t=!1}={}){this.painter.ctx.font=["normal"!=this.option.fontWeight&&this.option.fontWeight,"normal"!=this.option.fontStyle&&this.option.fontStyle,this.painter.upx2px(this.option.fontSize)+"px",this.option.fontFamily].filter(Boolean).join(" "),t||this.painter.ctx.setFillStyle(a(this,this.option.color)),this.painter.ctx.setFontSize(this.painter.upx2px(this.option.fontSize)),this.painter.ctx.setTextBaseline(this.option.baseline),this.painter.ctx.setTextAlign(this.option.align),this.painter.ctx.fillText(this.option.content,this.painter.upx2px(this.elementX),this.painter.upx2px(this.elementY)),console.debug("mp-painter:fillText:",this.option.content,"x=",this.elementX,"y=",this.elementY),this.paintTextDecoration()}paintTextDecoration(){"line-through"==this.option.textDecoration&&new c(this.painter,{top:this.elementY+.4*this.option.fontSize,left:this.elementX,dx:this.contentWidth,dy:0,color:this.option.color}).paint()}}class d{constructor(t){this.fontSize=t.fontSize,this.lineClamp=t.lineClamp||1/0,this.width=t.width,this.ctx=t.painter.ctx,this.painter=t.painter,this.content=t.content,this.lines=[],this.currentLineText="",this.position=0,this.endPostion=this.position,this.isOverflow=!1,this.isDry=!1,this.isFull=!1}split(){return this.painter.ctx.setFontSize(this.fontSize),this.fillText(),this.lines}minCharNumberInWidth(t){return Math.ceil(t/this.fontSize)}freeSpaceInCurrentLine(){if(this.currentLineText.length){let t=this.painter.ctx.measureTextWidth(this.currentLineText,this.fontSize);return this.width-(t||0)}return this.width}adjustCharNumberInCurrentLine(t){let e=this.currentLineText.length+t,i=this.content.length;e=Math.min(e,i),this.isDry=e==i,this.currentLineText=this.content.slice(0,e)}commitLine(){this.content=this.content.slice(this.currentLineText.length),this.lines.push(this.currentLineText),this.currentLineText="",this.lines.length==this.lineClamp&&(this.isFull=!0,0==this.isDry&&(this.isOverflow=!0))}handleOverflow(){let t=this.lines.pop();t=t.substring(0,Math.max(0,t.length-1))+"...",this.lines.push(t)}fillText(){let t=this.freeSpaceInCurrentLine();if(t<=0){if(this.adjustCharNumberInCurrentLine(-1),this.commitLine(),this.isOverflow&&this.handleOverflow(),this.isFull)return;t=this.freeSpaceInCurrentLine()}else if(this.isDry)return void this.commitLine();let e=this.minCharNumberInWidth(t);this.adjustCharNumberInCurrentLine(e),this.fillText()}}var f=function(t,e,i,n){return new(i||(i=Promise))((function(o,r){function s(t){try{a(n.next(t))}catch(t){r(t)}}function h(t){try{a(n.throw(t))}catch(t){r(t)}}function a(t){var e;t.done?o(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(s,h)}a((n=n.apply(t,e||[])).next())}))};class x extends s{constructor(t,e,i){var n,o,r,s,h,a,l;super(t,e,i),this.option=Object.assign(Object.assign({},e),{width:(n=e.width,null!=n?n:100),height:(o=e.height,null!=o?o:"auto"),fontSize:(r=e.fontSize,null!=r?r:30),content:(s=e.content,null!=s?s:""),lineHeight:(h=e.lineHeight,null!=h?h:40),lineClamp:(a=e.lineClamp,null!=a?a:0),color:(l=e.color,null!=l?l:"black")}),this.lines=[],this.option.content=u(this.option.content)}_layout(){return this.lines=new d({fontSize:this.option.fontSize,lineClamp:this.option.lineClamp,width:this.option.width,painter:this.painter,content:this.option.content}).split(),{width:this.option.width,height:"auto"==this.option.height?(this.lines.length-1)*this.option.lineHeight+this.option.fontSize:this.option.height}}paint(){return f(this,void 0,void 0,(function*(){this.painter.ctx.setFillStyle(a(this,this.option.color)),this.lines.map((t,e)=>{let i=Object.assign(Object.assign({},this.option),{type:"text",top:this.elementY+e*this.option.lineHeight,left:this.elementX,position:this.position,content:t});new p(this.painter,i).paint({inTextBlock:!0})})}))}}function m(t){let e=new Map;return function(i){return e.has(i)||e.set(i,t(i)),e.get(i)}}function w(){let t=!1;const e=t=>{let e=Object.getOwnPropertyDescriptors(Object.getPrototypeOf(t)),i={};for(let t in e){const n=e[t],o={};o.enumerable=n.enumerable,o.configurable=n.configurable,n.value&&"function"==typeof n.value&&(o.value=function(...t){return n.value.call(this.context,...t)}),n.value&&"function"!=typeof n.value&&(o.get=function(){return this.context[t]},o.set=function(e){this.context[t]=e}),n.get&&(o.get=function(){var t;return null===(t=n.get)||void 0===t?void 0:t.call(this.context)}),n.set&&(o.set=function(t){var e;null===(e=n.set)||void 0===e||e.call(this.context,t)}),i[t]=o}return Object.defineProperties({},i)},i=function(n){if(!(this instanceof i))throw new Error("mp-painter: `this` is not instance of `constructor`");if(this.context=n,!t)for(let n=this,o=Object.getPrototypeOf(n);null!==o;n=o,o=Object.getPrototypeOf(n))if(n.constructor===i){Object.setPrototypeOf(n,e(this.context)),t=!0;break}};return i}var y=function(t,e,i,n){return new(i||(i=Promise))((function(o,r){function s(t){try{a(n.next(t))}catch(t){r(t)}}function h(t){try{a(n.throw(t))}catch(t){r(t)}}function a(t){var e;t.done?o(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(s,h)}a((n=n.apply(t,e||[])).next())}))};class g extends(w()){constructor(t,e){super(e),this.painter=t}draw(t,e){e()}setFillStyle(t){super.fillStyle=t}setStrokeStyle(t){super.strokeStyle=t}drawImageWithSrc(t,e,i,n,o,r,s,h,a){const l=Object.create(null,{drawImage:{get:()=>super.drawImage}});return y(this,void 0,void 0,(function*(){let c=yield v(t);r&&s&&h&&a?l.drawImage.call(this,c,e,i,n,o,r,s,h,a):l.drawImage.call(this,c,e,i,n,o)}))}setTextAlign(t){super.textAlign=t}setTextBaseline(t){super.textBaseline="normal"===t?"alphabetic":t}setFontSize(t){var e,i;console.debug("set font size for h5, before is %s after is %s",super.font,null===(e=super.font)||void 0===e?void 0:e.replace(/\b\w+px\b/,this.painter.upx2px(t)+"px sans-serif")),super.font=null===(i=super.font)||void 0===i?void 0:i.replace(/\b\w+px\b/,this.painter.upx2px(t)+"px")}measureTextWidth(t,e){this.setFontSize(e);let i=this.measureText(t).width;return console.debug('measureText: result of measure text "%s" with font size %s is %s',t,this.font,i),null!=i?i:0}}function v(t){let e=new Image;return e.src=t,new Promise(t=>e.addEventListener("load",i=>t(e),{once:!0}))}var b=function(t,e,i,n){return new(i||(i=Promise))((function(o,r){function s(t){try{a(n.next(t))}catch(t){r(t)}}function h(t){try{a(n.throw(t))}catch(t){r(t)}}function a(t){var e;t.done?o(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(s,h)}a((n=n.apply(t,e||[])).next())}))};const S=m((function(t){return b(this,void 0,void 0,(function*(){try{let{width:i=100,height:n=100}=yield(e=uni.getImageInfo,function(t={}){return new Promise((i,n)=>{t.success=i,t.fail=n,e(t)})})({src:t});return{width:i,height:n}}catch(t){return console.log("mp-painter:getImageOriginSize: fail, use default size: width = 100, height = 100"),{width:100,height:100}}var e}))})),T=m((function(t){return b(this,void 0,void 0,(function*(){let e=yield v(t);return{width:e.naturalWidth,height:e.naturalHeight}}))}));class W extends s{constructor(t,e,i){var n,o,r,s;super(t,e,i),this.option={width:(n=e.width,null!=n?n:100),height:(o=e.height,null!=o?o:100),objectFit:(r=e.objectFit,null!=r?r:"fill"),objectPosition:(s=e.objectPosition,null!=s?s:["center","center"]),src:e.src}}_layout(){return{width:this.option.width,height:this.option.height}}paint(){return b(this,void 0,void 0,(function*(){let t=this.painter.upx2px;if(!this.option.src)return;let e=yield function(t,e){return b(this,void 0,void 0,(function*(){let i=t.platform;return"h5"!=i&&/^\./.test(e.src)||"h5"!=i&&/^\/static/.test(e.src)||"h5"!=i&&/^data:image\//.test(e.src)||"mp-alipay"==i&&/^https:\/\/resource\//.test(e.src)||"mp-weixin"==i&&/^wxfile:/.test(e.src)||"mp-baidu"==i&&/^bdfile:\/\/tmp/.test(e.src)?e.src:(console.log("mp-painter:绘制图片: 下载图片文件:",e.src),"h5"==i?e.src:yield(n=e.src,new Promise((t,e)=>o.downloadFile({url:n,success:e=>t(e.tempFilePath),fail:e}))).catch(t=>(console.log("mp-painter:下载错误: ",t),"")));var n}))}(this.painter,this.option);if(e)if(console.log("mp-painter:调用小程序drawImage,使用:",e),"fill"!=this.option.objectFit){let{sx:i,sy:n,sh:o,sw:r,dx:s,dy:h,dh:a,dw:l}=function(t,e,i){var n,o;let r=e.width/e.height,s=i.width/i.height,h=1;if(r>s&&"contain"==t.objectFit||r<=s&&"cover"==t.objectFit)h=i.width/e.width;else{if(!(r>s&&"cover"==t.objectFit||r<=s&&"contain"==t.objectFit))throw new Error("Unkonwn concreteScale");h=i.height/e.height}let a=e.width*h,l=e.height*h,c={left:0,center:.5,right:1}[(null===(n=t.objectPosition)||void 0===n?void 0:n[0])||"center"],u={top:0,center:.5,bottom:1}[(null===(o=t.objectPosition)||void 0===o?void 0:o[1])||"center"],p=(i.width-a)*c,d=(i.height-l)*u,f=(t,e)=>[(t-p)/h,(e-d)/h],[x,m]=f(0,0),[w,y]=f(i.width,i.height);return{sx:Math.max(x,0),sy:Math.max(m,0),sw:Math.min(w-x,e.width),sh:Math.min(y-m,e.height),dx:Math.max(p,0),dy:Math.max(d,0),dw:Math.min(a,i.width),dh:Math.min(l,i.height)}}({objectFit:this.option.objectFit,objectPosition:this.option.objectPosition},yield("h5"==this.painter.platform?T:S)(e),{width:this.option.width,height:this.option.height});this.painter.ctx.drawImageWithSrc(e,i,n,r,o,t(s+this.elementX),t(h+this.elementY),t(l),t(a))}else this.painter.ctx.drawImageWithSrc(e,t(this.elementX),t(this.elementY),t(this.option.width),t(this.option.height))}))}}class O extends class{constructor(t,e){var i,n;this.element=t,this.left=null!=(i=e.left)?i:0,this.top=null!=(n=e.top)?n:0}get painter(){return this.element.painter}get pathX(){return this.element.elementX+this.left}get pathY(){return this.element.elementY+this.top}}{constructor(t,e){super(t,e),this.option=e,this.option.borderRadius&&this.assertBorderRadius()}assertBorderRadius(){this.normalizedBorderRadius.some(t=>t<0)&&(console.warn("border radius must greater than 0, got:",this.normalizedBorderRadius.join(",")),this.option.borderRadius=0)}paint(){this.reduceBorderRadius();let[t,e,i,n]=this.normalizedBorderRadius,{ctx:o,upx2px:r}=this.painter;o.beginPath(),o.moveTo(r(this.pathX),r(this.pathY+t)),this.painter.ctx.arcTo(r(this.pathX),r(this.pathY),r(this.pathX+t),r(this.pathY),r(t)),this.painter.ctx.arcTo(r(this.pathX+this.option.width),r(this.pathY),r(this.pathX+this.option.width),r(this.pathY+e),r(e)),this.painter.ctx.arcTo(r(this.pathX+this.option.width),r(this.pathY+this.option.height),r(this.pathX+this.option.width-i),r(this.pathY+this.option.height),r(i)),this.painter.ctx.arcTo(r(this.pathX),r(this.pathY+this.option.height),r(this.pathX),r(this.pathY+this.option.height-n),r(n)),o.closePath()}get normalizedBorderRadius(){return"number"==typeof this.option.borderRadius?Array.from({length:4}).fill(this.option.borderRadius):[...this.option.borderRadius]}reduceBorderRadius(){let[t,e,i,n]=this.normalizedBorderRadius,o=Math.min(this.option.width/(t+e),this.option.height/(e+i),this.option.width/(n+i),this.option.height/(t+n));o>=1||(this.option.borderRadius=this.normalizedBorderRadius.map(t=>t*o))}}function P(t,e){switch(e.type){case"rounded-rect":return new O(t,e);default:throw new Error("Unkwon option type")}}class j extends s{constructor(t,e,i){var n,o,r,s,h,a,l;super(t,e,i),this.option={width:(n=e.width,null!=n?n:100),height:(o=e.height,null!=o?o:100),borderRadius:(r=e.borderRadius,null!=r?r:0),background:(s=e.background,null!=s?s:"transparent"),borderStyle:(h=e.borderStyle,null!=h?h:"solid"),borderWidth:(a=e.borderWidth,null!=a?a:0),borderColor:(l=e.borderColor,null!=l?l:"#000")}}_layout(){return{width:this.option.width,height:this.option.height}}paint(){(this.shouldFill||this.shouldStroke)&&(this.option.borderRadius?this.paintByPath():this.paintByRect())}get shouldFill(){return"trasparent"!==this.option.background}get shouldStroke(){return this.option.borderWidth>0}applyFillStyle(){this.painter.ctx.setFillStyle(a(this,this.option.background))}applyStrokeStyle(){var t,e;this.painter.ctx.setLineDash((t=this.option.borderStyle,{dashed:[e=this.option.borderWidth,e],solid:[10,0]}[t])),this.painter.ctx.lineWidth=this.painter.upx2px(this.option.borderWidth),this.painter.ctx.setStrokeStyle(this.option.borderColor)}paintByRect(){let t=[this.painter.upx2px(this.elementX),this.painter.upx2px(this.elementY),this.painter.upx2px(this.option.width),this.painter.upx2px(this.option.height)];this.shouldFill&&(this.applyFillStyle(),this.painter.ctx.fillRect(...t)),this.shouldStroke&&(this.applyStrokeStyle(),this.painter.ctx.strokeRect(...t))}paintByPath(){P(this,{type:"rounded-rect",height:this.option.height,width:this.option.width,borderRadius:this.option.borderRadius}).paint(),this.shouldFill&&(this.painter.ctx.setFillStyle(a(this,this.option.background)),this.painter.ctx.fill()),this.shouldStroke&&(this.applyStrokeStyle(),this.painter.ctx.stroke())}}var k=function(t,e,i,n){return new(i||(i=Promise))((function(o,r){function s(t){try{a(n.next(t))}catch(t){r(t)}}function h(t){try{a(n.throw(t))}catch(t){r(t)}}function a(t){var e;t.done?o(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(s,h)}a((n=n.apply(t,e||[])).next())}))};class F extends s{constructor(t,e,i){var n,o,r,s;super(t,e,i),this.childOffsetTop=0,this.childOffsetLeft=0,this.option={direction:(n=e.direction,null!=n?n:"vertical"),width:(o=e.width,null!=o?o:"auto"),height:(r=e.height,null!=r?r:"auto"),children:(s=e.children,null!=s?s:[])},this.children=this.option.children.map(t=>Y(this.painter,t,this))}_layout(){return k(this,void 0,void 0,(function*(){return yield this.layoutChildren(),{width:this.calcContainerWidth(),height:this.calcContainerHeight()}}))}layoutChildren(){return k(this,void 0,void 0,(function*(){for(let t of this.children)yield this.layoutChild(t)}))}layoutChild(t){return k(this,void 0,void 0,(function*(){yield t.layout(),"absolute"!=t.position&&("vertical"==this.option.direction?(t.offsetTop=this.childOffsetTop,this.childOffsetTop+=t.offsetHeight):(t.offsetLeft=this.childOffsetLeft,this.childOffsetLeft+=t.offsetWidth))}))}calcContainerWidth(){if("number"==typeof this.option.width)return this.option.width;switch(this.option.direction){case"vertical":return this.childrenMaxWidth();case"horizontal":return this.childOffsetLeft;default:throw new TypeError("Unknown direction")}}calcContainerHeight(){if("number"==typeof this.option.height)return this.option.height;switch(this.option.direction){case"vertical":return this.childOffsetTop;case"horizontal":return this.childrenMaxHeight();default:throw new TypeError("Unknown direction")}}paint(){return k(this,void 0,void 0,(function*(){for(let t of this.children)yield t.paint()}))}childrenMaxWidth(){return Math.max(...this.children.map(t=>t.offsetWidth),0)}childrenMaxHeight(){return Math.max(...this.children.map(t=>t.offsetHeight),0)}}var z=function(t,e,i,n){return new(i||(i=Promise))((function(o,r){function s(t){try{a(n.next(t))}catch(t){r(t)}}function h(t){try{a(n.throw(t))}catch(t){r(t)}}function a(t){var e;t.done?o(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(s,h)}a((n=n.apply(t,e||[])).next())}))};class I extends s{constructor(t,e,i){super(t,e,i),this.contentElement=Y(t,e.content,this),this.clipPath=P(this,e.path)}_layout(){return this.contentElement.layout()}paint(){return z(this,void 0,void 0,(function*(){this.painter.ctx.save(),yield this.clipPath.paint(),this.painter.ctx.clip(),yield this.contentElement.paint(),this.painter.ctx.restore()}))}}var C=function(t,e,i,n){return new(i||(i=Promise))((function(o,r){function s(t){try{a(n.next(t))}catch(t){r(t)}}function h(t){try{a(n.throw(t))}catch(t){r(t)}}function a(t){var e;t.done?o(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(s,h)}a((n=n.apply(t,e||[])).next())}))};class X extends s{constructor(t,e,i){var n,o;super(t,e,i),this.contentElement=Y(t,e.content,this),this.transformOptions=null!=(n=e.transform)?n:[],this.transformOrigin=null!=(o=e.transformOrigin)?o:["center","center"]}_layout(){return this.contentElement.layout()}paint(){return C(this,void 0,void 0,(function*(){this.painter.ctx.save(),this.withTransformOrigin(()=>this.transform()),yield this.contentElement.paint(),this.painter.ctx.restore()}))}transform(){this.transformOptions.forEach(t=>this.singleTransform(t))}singleTransform(t){var e,i,n,o;switch(t.type){case"translate":return this.painter.ctx.translate(this.painter.upx2px(null!=(e=t.x)?e:0),this.painter.upx2px(null!=(i=t.y)?i:0));case"rotate":return this.painter.ctx.rotate(t.rotate/180*Math.PI);case"scale":return this.painter.ctx.scale(null!=(n=t.scaleWidth)?n:1,null!=(o=t.scaleHeight)?o:1);case"set-matrix":return this.painter.ctx.setTransform(t.scaleX,t.skewX,t.skewY,t.scaleY,this.painter.upx2px(t.translateX),this.painter.upx2px(t.translateY));default:throw new Error("Unknown transform type.")}}withTransformOrigin(t){const e={x:this.elementX+this.contentWidth*{left:0,center:.5,right:1}[this.transformOrigin[0]],y:this.elementY+this.contentHeight*{top:0,center:.5,bottom:1}[this.transformOrigin[1]]};this.singleTransform({type:"translate",x:e.x,y:e.y}),t(),this.singleTransform({type:"translate",x:-e.x,y:-e.y})}}function Y(t,e,i){switch(e.type){case"text":return new p(t,e,i);case"text-block":return new x(t,e,i);case"image":return new W(t,e,i);case"line":return new c(t,e,i);case"rect":return new j(t,e,i);case"container":return new F(t,e,i);case"clip":return new I(t,e,i);case"transform":return new X(t,e,i);default:throw new TypeError("Unkown painter element type")}}let L=function(){var t;if("function"==typeof o.upx2px)return o.upx2px;let e=(null!=(t=o.getSystemInfoSync().screenWidth)?t:375)/750;return function(t){return t*e}}();const M=[.296,.313,.436,.638,.586,.89,.87,.256,.334,.334,.455,.742,.241,.433,.241,.427,.586,.586,.586,.586,.586,.586,.586,.586,.586,.586,.241,.241,.742,.742,.742,.483,1.031,.704,.627,.669,.762,.55,.531,.744,.773,.294,.396,.635,.513,.977,.813,.815,.612,.815,.653,.577,.573,.747,.676,1.018,.645,.604,.62,.334,.416,.334,.742,.448,.295,.553,.639,.501,.64,.567,.347,.64,.616,.266,.267,.544,.266,.937,.616,.636,.639,.64,.382,.463,.373,.616,.525,.79,.507,.529,.492,.334,.269,.334,.742,.296];var R=function(t,e,i,n){return new(i||(i=Promise))((function(o,r){function s(t){try{a(n.next(t))}catch(t){r(t)}}function h(t){try{a(n.throw(t))}catch(t){r(t)}}function a(t){var e;t.done?o(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(s,h)}a((n=n.apply(t,e||[])).next())}))};const E=w();class B extends E{constructor(t,e){super(e),this.painter=t}drawImageWithSrc(t,e,i,n,o,r,s,h,a){const l=Object.create(null,{drawImage:{get:()=>super.drawImage}});return R(this,void 0,void 0,(function*(){r&&s&&h&&a?l.drawImage.call(this,t,e,i,n,o,r,s,h,a):l.drawImage.call(this,t,e,i,n,o)}))}measureTextWidth(t,e){var i;return this.setFontSize(e),null!=(i=this.measureText(t).width)?i:0}}class H extends B{measureTextWidth(t,e){return t.split("").reduce((t,e)=>{let i=e.charCodeAt(0);return t+(M[i-32]||1)},0)*e}}var _=function(t,e,i,n){return new(i||(i=Promise))((function(o,r){function s(t){try{a(n.next(t))}catch(t){r(t)}}function h(t){try{a(n.throw(t))}catch(t){r(t)}}function a(t){var e;t.done?o(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(s,h)}a((n=n.apply(t,e||[])).next())}))};class D extends B{measureTextWidth(t,e){var i;return"top"==t&&console.log("measureText("+t+").width=",super.measureText(t).width),(null!=(i=super.measureText(t).width)?i:0)/10*e}drawImageWithSrc(t,e,i,n,o,r,s,h,a){const l=Object.create(null,{drawImageWithSrc:{get:()=>super.drawImageWithSrc}});return _(this,void 0,void 0,(function*(){r&&s&&h&&a?l.drawImageWithSrc.call(this,t,r,s,h,a,e,i,n,o):l.drawImageWithSrc.call(this,t,e,i,n,o)}))}}class U extends B{arcTo(t,e,i,n,o){return o<2?this.lineTo(t,e):super.arcTo(t,e,i,n,o)}measureTextWidth(t,e){return(t.includes("\n")||t.includes("\r"))&&console.warn(`mp-painter:measureText:字符串 "${t}" 中包含换行符,结果在 iPhone 上可能不准确`),super.measureTextWidth(t,e)}}i.d(e,"default",(function(){return N}));var A=function(t,e,i,n){return new(i||(i=Promise))((function(o,r){function s(t){try{a(n.next(t))}catch(t){r(t)}}function h(t){try{a(n.throw(t))}catch(t){r(t)}}function a(t){var e;t.done?o(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(s,h)}a((n=n.apply(t,e||[])).next())}))};class N{constructor(t,{platform:e=n,upx2px:i}={}){this.platform=e,this.upx2px=null!=i?i:L,"mp-alipay"==e&&(this.upx2px=t=>(null!=i?i:L)(2*t)),this.ctx=function(t,e){switch(t.platform){case"h5":return new g(t,e);case"mp-weixin":return new U(t,e);case"mp-alipay":return new H(t,e);case"mp-baidu":return new D(t,e);default:throw new Error("mp-painter: unexpect platform :"+t.platform)}}(this,t)}draw(t,e={}){return A(this,void 0,void 0,(function*(){let e=Y(this,t),i=yield e.layout();return yield e.paint(),yield new Promise(t=>this.ctx.draw(!0,t)),yield function(t=0){return new Promise(e=>setTimeout(e,t))}(100),i}))}createElement(t){return Y(this,t)}layout(t){return A(this,void 0,void 0,(function*(){return yield this.createElement(t).layout()}))}}}]); |
@@ -1,1 +0,1 @@ | ||
export declare function memorize<T>(fn: (arg: string) => T): (arg: string) => T; | ||
export declare function memorize<P, T>(fn: (arg: P) => T): (arg: P) => T; |
/// <reference types="uni-app" /> | ||
export declare type UniPlatforms = "mp-weixin" | "mp-alipay" | "mp-baidu"; | ||
export declare type UniPlatforms = "mp-weixin" | "mp-alipay" | "mp-baidu" | "h5"; | ||
export declare const PLATFORM: UniPlatforms; | ||
declare const _uni: Uni; | ||
declare const _uni: Uni | { | ||
upx2px: (x: number) => number; | ||
getSystemInfoSync: () => { | ||
screenWidth: number; | ||
}; | ||
downloadFile: (option: DownloadFileOption) => void | undefined; | ||
}; | ||
export { _uni as uni }; |
@@ -1,1 +0,1 @@ | ||
export declare let upx2px: (upx?: number | undefined) => number; | ||
export declare let upx2px: (x: number) => number; |
{ | ||
"name": "mp-painter", | ||
"version": "0.2.13", | ||
"version": "1.0.0-beta.1", | ||
"description": "A declarative canvas lib using with mini-program, espacially with uniapp.", | ||
"keywords": [ | ||
"canvas", | ||
"uniapp", | ||
"miniprogram", | ||
"poster" | ||
], | ||
"main": "dist/lib/painter.js", | ||
@@ -17,3 +23,2 @@ "types": "dist/lib/painter.d.ts", | ||
}, | ||
"keywords": [], | ||
"author": "https://github.com/xlfsummer", | ||
@@ -40,3 +45,7 @@ "license": "ISC", | ||
"webpack-cli": "^3.3.11" | ||
} | ||
}, | ||
"files": [ | ||
"src", | ||
"dist" | ||
] | ||
} |
@@ -1,6 +0,6 @@ | ||
import { calcConcreteRect } from "./object-sizing" | ||
import { calculateConcreteRect } from "./object-sizing" | ||
describe(calcConcreteRect, () => { | ||
describe(calculateConcreteRect, () => { | ||
it("图片胖, contain, 缩小", () => { | ||
expect(calcConcreteRect( | ||
expect(calculateConcreteRect( | ||
{ objectFit: "contain"}, | ||
@@ -16,3 +16,3 @@ { width: 200, height: 100 }, | ||
it("图片胖, contain, 放大", () => { | ||
expect(calcConcreteRect( | ||
expect(calculateConcreteRect( | ||
{ objectFit: "contain"}, | ||
@@ -28,3 +28,3 @@ { width: 50, height: 25 }, | ||
it("图片胖, cover, 缩小", () => { | ||
expect(calcConcreteRect( | ||
expect(calculateConcreteRect( | ||
{ objectFit: "cover" }, | ||
@@ -40,3 +40,3 @@ { width: 400, height: 200 }, | ||
it("图片胖, cover, 放大", () => { | ||
expect(calcConcreteRect( | ||
expect(calculateConcreteRect( | ||
{ objectFit: "cover" }, | ||
@@ -52,3 +52,3 @@ { width: 100, height: 50 }, | ||
it("图片瘦, contain, 缩小", () => { | ||
expect(calcConcreteRect( | ||
expect(calculateConcreteRect( | ||
{ objectFit: "contain" }, | ||
@@ -64,3 +64,3 @@ { width: 100, height: 200 }, | ||
it("图片瘦, contain, 放大", () => { | ||
expect(calcConcreteRect( | ||
expect(calculateConcreteRect( | ||
{ objectFit: "contain" }, | ||
@@ -76,3 +76,3 @@ { width: 25, height: 50 }, | ||
it("图片瘦, cover, 缩小", () => { | ||
expect(calcConcreteRect( | ||
expect(calculateConcreteRect( | ||
{ objectFit: "cover" }, | ||
@@ -88,3 +88,3 @@ { width: 200, height: 400 }, | ||
it("图片瘦, cover, 放大", () => { | ||
expect(calcConcreteRect( | ||
expect(calculateConcreteRect( | ||
{ objectFit: "cover" }, | ||
@@ -100,3 +100,3 @@ { width: 50, height: 100 }, | ||
it("图框比例相同", () => { | ||
expect(calcConcreteRect( | ||
expect(calculateConcreteRect( | ||
{ objectFit: "cover" }, | ||
@@ -110,3 +110,3 @@ { width: 100, height: 100 }, | ||
expect(calcConcreteRect( | ||
expect(calculateConcreteRect( | ||
{ objectFit: "contain" }, | ||
@@ -122,3 +122,3 @@ { width: 100, height: 100 }, | ||
it("图框比例相同 - 缩放", () => { | ||
expect(calcConcreteRect( | ||
expect(calculateConcreteRect( | ||
{ objectFit: "cover" }, | ||
@@ -132,3 +132,3 @@ { width: 200, height: 200 }, | ||
expect(calcConcreteRect( | ||
expect(calculateConcreteRect( | ||
{ objectFit: "contain" }, | ||
@@ -135,0 +135,0 @@ { width: 50, height: 50 }, |
import Painter from "./painter"; | ||
import { PainterContext } from "./painter-context/index"; | ||
@@ -15,3 +16,3 @@ interface ILineSpliterContextOption { | ||
width: number; | ||
ctx: CanvasContext; | ||
ctx: PainterContext; | ||
painter: Painter; | ||
@@ -46,3 +47,3 @@ content: string; | ||
// 测量文本前先设置字体大小 | ||
this.ctx.setFontSize(this.fontSize); | ||
this.painter.ctx.setFontSize(this.fontSize); | ||
this.fillText(); | ||
@@ -60,3 +61,3 @@ return this.lines; | ||
else { | ||
let width = this.painter.measureText(this.currentLineText, this.fontSize); | ||
let width = this.painter.ctx.measureTextWidth(this.currentLineText, this.fontSize); | ||
return this.width - (width || 0); | ||
@@ -63,0 +64,0 @@ } |
@@ -87,7 +87,7 @@ import Painter from "../painter"; | ||
childrenMaxWidth(){ | ||
return Math.max(...this.children.map(el => el.offsetWidth)) | ||
return Math.max(...this.children.map(el => el.offsetWidth), 0); | ||
} | ||
childrenMaxHeight(){ | ||
return Math.max(...this.children.map(el => el.offsetHeight)) | ||
return Math.max(...this.children.map(el => el.offsetHeight), 0); | ||
} | ||
} |
@@ -9,5 +9,7 @@ import Painter from "../painter"; | ||
const getImageOriginSize = memorize(async function (src: string): Promise<Size>{ | ||
import { normalizeImageResource as normalizeImageResourceH5 } from "../painter-context/context-h5"; | ||
const getImageOriginSize = memorize(async function (img: string): Promise<Size>{ | ||
try { | ||
let { width = 100, height = 100 } = await promisify(uni.getImageInfo)({ src }); | ||
let { width = 100, height = 100 } = await promisify(uni.getImageInfo)({ src: img }); | ||
return { width, height }; | ||
@@ -20,2 +22,7 @@ }catch(e){ | ||
const getImageOriginSizeH5 = memorize(async function (src: string): Promise<Size>{ | ||
let img = await normalizeImageResourceH5(src); | ||
return { width: img.naturalWidth, height: img.naturalHeight }; | ||
}); | ||
export interface PainterImageElementOption extends PainterElementOption{ | ||
@@ -35,3 +42,3 @@ type: "image"; | ||
* - contain 等比缩放,使图片刚好能完整显示出来 | ||
* - cover 等比缩放,使图片更好能占满容器 | ||
* - cover 等比缩放,使图片刚好能占满容器 | ||
*/ | ||
@@ -66,3 +73,3 @@ objectFit?: ObjectFit; | ||
let src = await normalizeImageSrc(this.painter, this.option); | ||
let src = await normalizeImageResource(this.painter, this.option); | ||
if(!src) return ; | ||
@@ -77,3 +84,3 @@ | ||
}, | ||
await getImageOriginSize(src), | ||
await (this.painter.platform == "h5" ? getImageOriginSizeH5 : getImageOriginSize)(src), | ||
{ | ||
@@ -84,3 +91,3 @@ width: this.option.width, | ||
this.painter.drawImage(src, sx, sy, sw, sh, | ||
this.painter.ctx.drawImageWithSrc(src, sx, sy, sw, sh, | ||
upx2px(dx + this.elementX), | ||
@@ -92,3 +99,3 @@ upx2px(dy + this.elementY), | ||
} else { | ||
this.painter.ctx.drawImage(src, | ||
this.painter.ctx.drawImageWithSrc(src, | ||
upx2px(this.elementX), | ||
@@ -103,3 +110,4 @@ upx2px(this.elementY), | ||
async function normalizeImageSrc(painter: Painter, image: Pick<PainterImageElementOption, "src">) { | ||
async function normalizeImageResource(painter: Painter, image: Pick<PainterImageElementOption, "src">): | ||
Promise<undefined | string> { | ||
let platform = painter.platform; | ||
@@ -126,6 +134,6 @@ /** | ||
// 本地图片 | ||
LOCAL_FILE_RELATIVE_PATH_REG.test(image.src) || | ||
LOCAL_FILE_ABSOLUTE_PATH_REG.test(image.src) || | ||
platform != "h5" && LOCAL_FILE_RELATIVE_PATH_REG.test(image.src) || | ||
platform != "h5" && LOCAL_FILE_ABSOLUTE_PATH_REG.test(image.src) || | ||
// base64 图片 | ||
BASE64_URL_REG.test(image.src) || | ||
platform != "h5" && BASE64_URL_REG.test(image.src) || | ||
// 支付宝中需要先下载图片再绘制 | ||
@@ -141,3 +149,8 @@ platform == "mp-alipay" && ALIPAY_LOCAL_RESOURCE_URL_REG.test(image.src) || | ||
console.log("mp-painter:绘制图片: 下载图片文件:", image.src); | ||
return await downloadFileToLocal(image.src).catch(err => (console.log("mp-painter:下载错误: ", err), "")); | ||
if(platform == "h5"){ | ||
return image.src; | ||
}else{ | ||
return await downloadFileToLocal(image.src).catch(err => (console.log("mp-painter:下载错误: ", err), "")); | ||
} | ||
} |
@@ -47,3 +47,3 @@ import Painter from "../painter"; | ||
this.painter.ctx.setLineDash(this.option.dashPattern.map(x => this.painter.upx2px(x))); | ||
this.painter.setStrokeStyle(createFillStrokeStyle(this, this.option.color)); | ||
this.painter.ctx.setStrokeStyle(createFillStrokeStyle(this, this.option.color)); | ||
this.painter.ctx.lineWidth = lineWidth; | ||
@@ -50,0 +50,0 @@ this.painter.ctx.stroke(); |
@@ -82,3 +82,3 @@ import Painter from "../painter"; | ||
private applyFillStyle(){ | ||
this.painter.setFillStyle(createFillStrokeStyle(this, this.option.background)); | ||
this.painter.ctx.setFillStyle(createFillStrokeStyle(this, this.option.background)); | ||
} | ||
@@ -89,3 +89,3 @@ | ||
this.painter.ctx.lineWidth = this.painter.upx2px(this.option.borderWidth); | ||
this.painter.setStrokeStyle(this.option.borderColor); | ||
this.painter.ctx.setStrokeStyle(this.option.borderColor); | ||
} | ||
@@ -122,3 +122,3 @@ | ||
if(this.shouldFill){ | ||
this.painter.setFillStyle(createFillStrokeStyle(this, this.option.background)); | ||
this.painter.ctx.setFillStyle(createFillStrokeStyle(this, this.option.background)); | ||
this.painter.ctx.fill(); | ||
@@ -125,0 +125,0 @@ } |
@@ -62,3 +62,3 @@ import Painter from "../painter"; | ||
// 如果单独设置,则计算渐变填充坐标时会相对于每一行的文本来计算 | ||
this.painter.setFillStyle(createFillStrokeStyle(this, this.option.color)); | ||
this.painter.ctx.setFillStyle(createFillStrokeStyle(this, this.option.color)); | ||
@@ -65,0 +65,0 @@ this.lines.map((line, row) => { |
@@ -52,3 +52,3 @@ import Painter from "../painter"; | ||
_layout(){ | ||
let textWidth = this.option.width ?? this.painter.measureText(this.option.content, this.option.fontSize); | ||
let textWidth = this.option.width ?? this.painter.ctx.measureTextWidth(this.option.content, this.option.fontSize); | ||
return { | ||
@@ -71,3 +71,3 @@ width: textWidth, | ||
} else { | ||
this.painter.setFillStyle(createFillStrokeStyle(this, this.option.color)); | ||
this.painter.ctx.setFillStyle(createFillStrokeStyle(this, this.option.color)); | ||
} | ||
@@ -78,4 +78,2 @@ | ||
this.painter.ctx.setTextAlign(this.option.align); | ||
console.debug("mp-painter:fillText:", this.option.content, "x=", this.elementX, "y=", this.elementY); | ||
this.painter.ctx.fillText( | ||
@@ -86,2 +84,4 @@ this.option.content, | ||
); | ||
console.debug("mp-painter:fillText:", this.option.content, "x=", this.elementX, "y=", this.elementY); | ||
@@ -88,0 +88,0 @@ this.paintTextDecoration(); |
@@ -48,3 +48,3 @@ import { PainterPath, PainterPathOption, } from "./base"; | ||
// left top | ||
this.painter.arcTo( | ||
this.painter.ctx.arcTo( | ||
upx2px(this.pathX), | ||
@@ -58,3 +58,3 @@ upx2px(this.pathY), | ||
// right top | ||
this.painter.arcTo( | ||
this.painter.ctx.arcTo( | ||
upx2px(this.pathX + this.option.width), | ||
@@ -68,3 +68,3 @@ upx2px(this.pathY), | ||
// right bottom | ||
this.painter.arcTo( | ||
this.painter.ctx.arcTo( | ||
upx2px(this.pathX + this.option.width), | ||
@@ -78,3 +78,3 @@ upx2px(this.pathY + this.option.height), | ||
// left bottom | ||
this.painter.arcTo( | ||
this.painter.ctx.arcTo( | ||
upx2px(this.pathX), | ||
@@ -81,0 +81,0 @@ upx2px(this.pathY + this.option.height), |
import { delay } from "../utils/delay"; | ||
import { PLATFORM, UniPlatforms } from "../utils/platform"; | ||
import { CHAR_WIDTH_SCALE_MAP } from "./const"; | ||
import { BuiltInPainterElementOption, createElement } from "./painter-element/index"; | ||
import { upx2px as defaultUpx2px } from "../utils/upx2px"; | ||
import { FillStrokeStyle } from "./value"; | ||
import { adaptContext, PainterContext } from "./painter-context/index"; | ||
interface IPanterOption { | ||
platform?: UniPlatforms | ||
upx2px?: (upx: number) => number | ||
platform?: UniPlatforms | ||
} | ||
/** 单次绘制选项 */ | ||
interface IDrawOption { | ||
} | ||
export default class Painter { | ||
ctx: PainterContext; | ||
upx2px: NonNullable<IPanterOption["upx2px"]> | ||
platform: NonNullable<IPanterOption["platform"]> | ||
ctx: CanvasContext; | ||
upx2px: (upx: number) => number | ||
platform: UniPlatforms | ||
constructor(ctx: CanvasContext, { | ||
platform = PLATFORM, | ||
upx2px | ||
}: IPanterOption = {}){ | ||
this.ctx = ctx; | ||
}: IPanterOption = {}){ | ||
this.platform = platform; | ||
this.upx2px = upx2px ?? defaultUpx2px; | ||
this.upx2px = upx2px ?? defaultUpx2px; | ||
if(platform == "mp-alipay"){ | ||
this.upx2px = (x: number) => (upx2px ?? defaultUpx2px)(x * 2); | ||
} | ||
this.ctx = adaptContext(this, ctx); | ||
} | ||
async draw(element: BuiltInPainterElementOption){ | ||
let size = await this._drawObj(element); | ||
async draw(elementOption: BuiltInPainterElementOption, drawOption: IDrawOption = {}){ | ||
// debug("call context draw method"); | ||
await new Promise(resolve => this.ctx.draw(true, resolve)); | ||
// debug("context draw method done"); | ||
// 在 draw 的 callback 中, canvas 还没有真正绘制完成,此时 resolve 会导致文字错乱 | ||
await delay(100); | ||
return size; | ||
} | ||
async _drawObj(paintObj: BuiltInPainterElementOption){ | ||
let element = createElement(this, paintObj); | ||
let element = createElement(this, elementOption); | ||
let size = await element.layout(); | ||
await element.paint(); | ||
return size; | ||
} | ||
/** | ||
* 兼容设置填充样式 | ||
*/ | ||
setFillStyle(color: FillStrokeStyle){ | ||
if(this.platform == "mp-baidu"){ | ||
this.ctx.setFillStyle(color); | ||
}else{ | ||
this.ctx.fillStyle = color; | ||
} | ||
} | ||
await new Promise<void>(resolve => this.ctx.draw(true, resolve)); | ||
/** | ||
* 兼容设置描边样式 | ||
*/ | ||
setStrokeStyle(color: FillStrokeStyle){ | ||
if(this.platform == "mp-baidu"){ | ||
this.ctx.setStrokeStyle(color); | ||
}else{ | ||
this.ctx.strokeStyle = color; | ||
} | ||
// 在 draw 的 callback 中, canvas 还没有真正绘制完成,此时 resolve 会导致文字错乱 | ||
await delay(100); | ||
return size; | ||
} | ||
/** 测量文本宽度 */ | ||
measureText(text: string, fontSize: number){ | ||
if(this.platform == "mp-weixin" && (text.includes("\n") || text.includes("\r"))){ | ||
console.warn(`mp-painter:measureText:字符串 "${text}" 中包含换行符,结果在 iPhone 上可能不准确`); | ||
} | ||
if(this.platform == "mp-baidu"){ | ||
// 百度测量的字号是以 10 为基准的,不会根据字号设置而变化 | ||
let width = this.ctx.measureText(text).width; | ||
if(width) return width / 10 * fontSize; | ||
} else if(this.platform == "mp-alipay") { | ||
// 在支付宝 iOS 中获取字符串宽度时, 如果字符串数量较多,可能获取不到正确的宽度 | ||
// 获取到的宽度会始终比换行所需的宽度小,无法正确换行。 | ||
return text.split("").reduce((widthScaleSum, char) => { | ||
let code = char.charCodeAt(0); | ||
let widthScale = CHAR_WIDTH_SCALE_MAP[code - 0x20] || 1; | ||
return widthScaleSum + widthScale; | ||
}, 0) * fontSize; | ||
} else { | ||
this.ctx.setFontSize(fontSize); | ||
let width = this.ctx.measureText(text).width; | ||
if(width) return width; | ||
} | ||
return text.length * fontSize; | ||
/** 创建元素对象 */ | ||
createElement(elementOption: BuiltInPainterElementOption){ | ||
return createElement(this, elementOption); | ||
} | ||
/** 兼容地,根据控制点和半径绘制圆弧路径 */ | ||
arcTo(x1: number, y1: number, x2: number, y2: number, radius: number){ | ||
// fix issue #9, 微信中, 如果 radius < 2, arcTo 命令会被忽略 | ||
if(radius < 2){ | ||
return this.ctx.lineTo(x1, y1); | ||
} | ||
return this.ctx.arcTo(x1, y1, x2, y2, radius); | ||
/** 获取指定元素的尺寸 */ | ||
async layout(elementOption: BuiltInPainterElementOption){ | ||
return await this.createElement(elementOption).layout(); | ||
} | ||
/** 兼容绘制图片 */ | ||
drawImage(imageResource: string, sx: number, sy: number, sWidth: number, sHeigt: number, dx: number, dy: number, dWidth: number, dHeight: number){ | ||
if(arguments.length != 9){ | ||
//@ts-ignore | ||
return this.ctx.drawImage.call(this, ...arguments); | ||
} | ||
if(this.platform == "mp-baidu"){ | ||
return this.ctx.drawImage(imageResource, dx, dy, dWidth, dHeight, sx, sy, sWidth, sHeigt); | ||
}else{ | ||
return this.ctx.drawImage(imageResource, sx, sy, sWidth, sHeigt, dx, dy, dWidth, dHeight); | ||
} | ||
} | ||
} |
import { uni } from "../utils/platform" | ||
export function downloadFileToLocal(path: string): Promise<string | undefined> { | ||
return new Promise((resolve, reject) => | ||
@@ -5,0 +6,0 @@ uni.downloadFile({ |
@@ -1,8 +0,9 @@ | ||
export function memorize<T>(fn: (arg: string) => T){ | ||
let map = Object.create(null); | ||
return function (arg: string): T { | ||
if(!(arg in map)) | ||
map[arg] = fn(arg); | ||
return map[arg]; | ||
export function memorize<P, T>(fn: (arg: P) => T){ | ||
let map = new Map<P, T>(); | ||
return function (arg: P): T { | ||
if(!map.has(arg)) | ||
map.set(arg, fn(arg)); | ||
return map.get(arg)!; | ||
} | ||
} |
@@ -1,2 +0,2 @@ | ||
export type UniPlatforms = "mp-weixin" | "mp-alipay" | "mp-baidu"; | ||
export type UniPlatforms = "mp-weixin" | "mp-alipay" | "mp-baidu" | "h5"; | ||
@@ -15,2 +15,4 @@ declare var wx: Uni | ||
return "mp-weixin" | ||
if(typeof window == "object") | ||
return "h5" | ||
return "mp-weixin" | ||
@@ -27,2 +29,9 @@ })(); | ||
if(typeof window != "undefined") | ||
return { | ||
upx2px: (x: number) => x, | ||
getSystemInfoSync: () => ({ screenWidth: window.innerWidth }), | ||
downloadFile: (option: DownloadFileOption) => option.success?.({tempFilePath: option.url}) | ||
}; | ||
throw new Error("enviroment not support"); | ||
@@ -29,0 +38,0 @@ })(); |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 1 instance in 1 package
126584
84
2416
0