一个仿Vue风格的图片上传工具,但不是Vue的插件,只是使用方式类似于Vue风格,原生无依赖,数据与ui分离,使用插件方式拓展方法
存在的bug
-
gif图无法进行任何压缩、绘图操作,直接上传
-
没有绘图操作时不要写drawStart和drawEnd方法,会导致图片进入canvas操作,从而使图片变大。(插件上设计的问题,暂未找到解决办法)
use browser
<script type="text/javascript" src="./index.js"></script>
use module
npm i mgue --save
import mgue from 'mgue'
// use plugins
import fillTextPlugin from 'mgue/mgueFillText'
import fillRectPlugin from 'mgue/mgueFillRect'
import fillCirclePlugin from 'mgue/mgueFillCircle'
import rotatePlugin from 'mgue/mgueRotate'
import scalePlugin from 'mgue/mgueScale'
import translatePlugin from 'mgue/mgueTranslate'
// 注册插件
Mgue.use(fillTextPlugin)
Mgue.use(fillRectPlugin)
Mgue.use(fillCirclePlugin)
// 旋转,缩放,位移插件,使用方法参考demo目录下的文件,原理差不多
Mgue.use(rotatePlugin)
Mgue.use(scalePlugin)
Mgue.use(translatePlugin)
插件使用(是不是很像Vue,就是参(chao)考(xi)了Vue的思路!0.0)
// 编写插件
let fillTextPlugin = {}
fillTextPlugin.install = function (mgue, options) {
console.log(options)
// 1. 添加全局方法或属性,一般不使用
mgue.myGlobalMethod = function () {
console.log('myGlobalMethod')
// 逻辑...
}
// 2. 添加实例方法
mgue.prototype.$fillText = function (ctx, opts) {
ctx.font = opts.font;
ctx.fillStyle = opts.fillStyle;
ctx.textAlign = opts.textAlign;
ctx.fillText(opts.txt, opts.w , opts.h);
}
}
if (typeof exports == "object") {
module.exports = fillTextPlugin;
} else if (typeof define == "function" && define.amd) {
define([], function () {
return fillTextPlugin
})
} else if (window) {
window.fillTextPlugin = fillTextPlugin;
}
// 注册插件
mgue.use(MyPlugin, {
params: 'test' // 可以添加额外的参数
})
// 使用插件
var gradient = ctx.createLinearGradient(0, 0, canvas.width, 0)
gradient.addColorStop("0", "white")
gradient.addColorStop("0.5", "#00bfff")
gradient.addColorStop("1.0", "white")
// 使用插件,这是个加文字到图片上的插件
this.$fillText(ctx, {
font: `${img.width / 10}px microsoft yahei`,
fillStyle: gradient,
txt: '居中填充文字',
textAlign: 'center',
w: canvas.width / 2,
h: canvas.height / 2
})
// 插件的使用一般是对canvas进行操作,所以插件一般用在drawStart方法里面,该方法会暴露出当前的绘图对象和img本身// ctx, img, canvas,目录下有三个常用方法的插件,用于添加文本,图形,可用于加水印标识等等,也可自己写插件,按照上面// 的方法使用即可,本意上就是对canvas进行操作,只要有足够的绘图功底,Nothing is impossible!!! { // 绘图开始钩子 let ctx img canvas = this this}
示例,可直接下载此项目,查看demo文件夹下对应的文件
后端代码以node为示例,基于express,依赖formidable库
var express = ;var router = express;var formidable = ;var fs = ; routerall'*' { res; res; res; res; res; ;}; router; moduleexports = router;
参考文献