vue实现裁切图片同时实现放大、缩小、旋转功能

2020-06-16 06:13:07易采站长站整理

methods: {
// 旋转操作
rotate () {
const {$options, draw} = this
this.deg = (this.deg + Math.PI /2)% (Math.PI * 2)
draw($options.img, $options.nX + $options.xV, $options.nY + $options.yV, this.scale, this.deg)
},
// 处理放大
handleScale (flag) {
const {$options, draw, deg} = this
flag && this.scale > 0.1 && (this.scale = this.scale - 0.1)
!flag && this.scale < 1.9 && (this.scale = this.scale + 0.1)
$options.img && draw($options.img, $options.nX + $options.xV, $options.nY + $options.yV, this.scale, deg)
},
// 模拟file 点击事件
dispatchUpload (e) {
this.clearState()
const {file} = this.$options
e.preventDefault()
file.click()
},
// 读取 input file 信息
readFileMsg () {
const {file} = this.$options
const {draw, createImage, $options: {nX, nY}, scale, deg} = this
const wFile = file.files[0] const reader = new FileReader()
reader.onload = (e) => {
const img = createImage(e.target.result, (img) => {
draw(img, nX, nY, scale, deg)
})
file.value = null
}
reader.readAsDataURL(wFile)
},
// 生成 图像
createImage (src, cb) {
const img = new Image()
this.$el.append(img)
img.className = 'base64-hidden'
img.onload = () => {
cb(img)
}
img.src = src
this.$options.img = img
},
// 操作画布画图
draw (img, x = 0, y = 0, scale = 0.5,deg = Math.PI ) {
const {ctx} = this.$options
let {width, height} = this
// 图片尺寸
let imgW = img.offsetWidth
let imgH = img.offsetHeight
ctx.save()
ctx.clearRect( 0, 0, width, height)
ctx.translate( width / 2, height / 2, img)
ctx.rotate(deg)
ctx.drawImage(img, x, y, imgW * scale, imgH * scale)
ctx.restore()
},
// ... 事件绑定
handleClip (e) {
const {handleMove, $options, deg} = this
if (!$options.img) {
return
}
Object.assign(this.$options, {
x: e.screenX,
y: e.screenY
})
on({
el: window,
type: 'mousemove',
fn: handleMove
})
once({
el: window,
type: 'mouseup',
fn: (e) =>{
console.log('down')
switch (deg) {
case 0: {
Object.assign($options, {
nX: $options.nX + $options.xV,