vue 实现 裁切图片 同时有放大、缩小、旋转功能
实现效果:
- 裁切指定区域内的图片
- 旋转图片
- 放大图片
- 输出bolb 格式数据 提供给 formData 对象
效果图
大概原理:
利用h5 FileReader 对象, 获取 <input type="file"/> “上传到浏览器的文件” ,文件形式 为base64形式, 把 base64 赋给canvas的上下文。
然后给canvas 元素上加入对(mousedown)监听事件。 当用户鼠标左键在canvas按下时:
- 挂载对 window 对象mousemove事件 ---> 获取 鼠标移动x,y距离.从而操作 canvas里的图像的位置移动。
- 挂载对 window 对象mouseup 事件, 清除 mousemove事件的绑定。(同时该事件触发后会被删除)
剩下的 放大、缩小 、 旋转 是对 canvas 对象的操作/坐标体系的操作。具体api详见mdn canvas 文档
代码
dom.js
export const on = ({el, type, fn}) => {
if (typeof window) {
if (window.addEventListener) {
el.addEventListener(type, fn, false)
} else {
el.attachEvent(`on${type}`, fn)
}
}
}
export const off = ({el, type, fn}) => {
if (typeof window) {
if (window.addEventListener) {
el.removeEventListener(type, fn)
} else {
el.detachEvent(`on${type}`, fn)
}
}
}
export const once = ({el, type, fn}) => {
const hyFn = (event) => {
try {
fn(event)
}
finally {
off({el, type, fn: hyFn})
}
}
on({el, type, fn: hyFn})
}
// 最后一个
export const fbTwice = ({fn, time = 300}) => {
let [cTime, k] = [null, null]
// 获取当前时间
const getTime = () => new Date().getTime()
// 混合函数
const hyFn = () => {
const ags = argments
return () => {
clearTimeout(k)
k = cTime = null
fn(...ags)
}
}
return () => {
if (cTime == null) {
k = setTimeout(hyFn(...arguments), time)
cTime = getTime()
} else {
if ( getTime() - cTime < 0) {
// 清除之前的函数堆 ---- 重新记录
clearTimeout(k)
k = null
cTime = getTime()
k = setTimeout(hyFn(...arguments), time)
}
}}
}
export const contains = function(parentNode, childNode) {
if (parentNode.contains) {
return parentNode != childNode && parentNode.contains(childNode)
} else {
return !!(parentNode.compareDocumentPosition(childNode) & 16)
}
}
export const addClass = function (el, className) {
if (typeof el !== "object") {
console.log('el is not elem')
return null
}
let classList = el['className']
classList = classList === '' ? [] : classList.split(/\s+/)
if (classList.indexOf(className) === -1) {
classList.push(className)
el.className = classList.join(' ')
} else {
console.warn('warn className current')
}
}
export const removeClass = function (el, className) {
let classList = el['className']
classList = classList === '' ? [] : classList.split(/\s+/)
classList = classList.filter(item => {
return item !== className
})
el.className = classList.join(' ')
}
export const delay = ({fn, time}) => {
let oT = null
let k = null
return () => {
// 当前时间
let cT = new Date().getTime()
const fixFn = () => {
k = oT = null
fn()
}
if (k === null) {
oT = cT
k = setTimeout(fixFn, time)
return
}
if (cT - oT < time) {
oT = cT
clearTimeout(k)
k = setTimeout(fixFn, time)
}
}
}
export const Event = function () {
// 类型
this.typeList = {}
}
Event.prototype.on = function ({type, fn}){
if (this.typeList.hasOwnProperty(type)) {
this.typeList[type].push(fn)
} else {
this.typeList[type] = []
this.typeList[type].push(fn)
}
}
Event.prototype.off = function({type, fn}) {
if (this.typeList.hasOwnProperty(type)) {
let list = this.typeList[type]
let index = list.indexOf(fn)
if (index !== -1 ) {
list.splice(index, 1)
}
} else {
console.warn('not has this type')
}
}
Event.prototype.once = function ({type, fn}) {
const fixFn = () => {
fn()
this.off({type, fn: fixFn})
}
this.on({type, fn: fixFn})
}
Event.prototype.trigger = function (type){
if (this.typeList.hasOwnProperty(type)) {
this.typeList[type].forEach(fn => {
fn()
})
}
}
组件模板
<template>
<div class="jc-clip-image" :style="{width: `${clip.width}`}">
<canvas ref="ctx"
:width="clip.width"
:height="clip.height"
@mousedown="handleClip($event)"
>
</canvas>
<input type="file" ref="file" @change="readFileMsg($event)">
<div class="clip-scale-btn">
<a class="add" @click="handleScale(false)">+</a>
<a @click="rotate" class="right-rotate">转</a>
<a class="poor" @click="handleScale(true)">-</a>
<span>{{scale}}</span>
</div>
<div class="upload-warp">
<a class="upload-btn" @click="dispatchUpload($event)">upload</a>
<a class="upload-cancel">cancel</a>
</div>
<div class="create-canvas">
<a class="to-send-file" @click="outFile" title="请打开控制台">生成文件</a>
</div>
</div>
</template>
<script>
import {on, off, once} from '../../utils/dom'
export default {
ctx: null,
file: null,
x: 0, // 点击canvas x 鼠标地址
y: 0,// 点击canvas y 鼠标地址
xV: 0, // 鼠标移动 x距离
yV: 0, // 鼠标移动 y距离
nX: 0, // 原始坐标点 图像 x
nY: 0,// 原始坐标点 图像 y
img: null,
props: {
src: {
type: String,
default: null
},
clip: {
type: Object,
default () {
return {width: '200px', height: '200px'}
}
}
},
data () {
return {
isShow: false,
base64: null,
scale: 1.5, //放大比例
deg: 0 //旋转角度
}
},
computed: {
width () {
const {clip} = this
return parseFloat(clip.width.replace('px', ''))
},
height () {
const {clip} = this
return parseFloat(clip.height.replace('px', ''))
}
},
mounted () {
const {$options, $refs, width, height} = this
// 初始化 canvas file nX nY
Object.assign($options, {
ctx: $refs.ctx.getContext('2d'),
file: $refs.file,
nX: -width / 2,
nY: -height / 2
})
},
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,
nY: $options.nY + $options.yV,
xV: 0,
yV: 0
})
break;
}
case Math.PI / 2: {
Object.assign($options, {
nX: $options.nY + $options.yV,
nY: $options.nX - $options.xV,
xV: 0,
yV: 0
})
break;
}
case Math.PI: {
Object.assign($options, {
nX: $options.nX - $options.xV,
nY: $options.nY - $options.yV,
xV: 0,
yV: 0
})
break;
}
default: {
// $options.nY - $options.yV, $options.nX + $options.xV
Object.assign($options, {
nX: $options.nY - $options.yV,
nY: $options.nX + $options.xV,
xV: 0,
yV: 0
})
}
}
off({
el: window,
type: 'mousemove',
fn: handleMove
})
}
})
},
// ... 处理鼠标移动
handleMove (e){
e.preventDefault()
e.stopPropagation()
const {$options, draw, scale, deg} = this
Object.assign($options, {
xV: e.screenX - $options.x,
yV: e.screenY - $options.y
})
switch (deg) {
case 0: {
draw($options.img, $options.nX + $options.xV, $options.nY + $options.yV, scale, deg)
break;
}
case Math.PI / 2: {
draw($options.img, $options.nY + $options.yV, $options.nX - $options.xV, scale, deg)
break;
}
case Math.PI: {
draw($options.img, $options.nX - $options.xV, $options.nY - $options.yV, scale, deg)
break;
}
default: {
draw($options.img, $options.nY - $options.yV, $options.nX + $options.xV, scale, deg)
break;
}
}
},
// 清除状态
clearState () {
const {$options, width, height} = this
if ($options.img) {
this.$el.removeChild($options.img)
Object.assign($options, {
x: 0,
y: 0,
xV: 0,
yV: 0,
nX: -width / 2,
nY: -height / 2,
img: null,
})
}
},
// 输出文件
outFile () {
const {$refs: {ctx}} = this
console.log(ctx.toDataURL())
ctx.toBlob((blob) => {console.log(blob)})
}
}
}
</script>
<style>
@component-namespace jc {
@component clip-image{
position: relative;
width: 100%;
canvas {
position: relative;
width: 100%;
height: 100%;
cursor: pointer;
box-shadow: 0 0 3px #333;
}
input {
display: none;
}
.base64-hidden {
position: absolute;
top: 0;
left: 0;
display: block;
width: 100%;
height: auto;
z-index: -999;
opacity: 0;
}
.clip-scale-btn {
position: relative;
@utils-clearfix;
margin-bottom: 5px;
text-align: center;
a {
float: left;
width: 20px;
height: 20px;
border-radius: 50%;
color: #fff;
background: #49a9ee;
text-align: center;
cursor: pointer;
}
&>.poor, &>.right-rotate {
float: right;
}
&>span{
position: absolute;
z-index: -9;
top: 0;
left: 0;
display: block;
position: relative;
width: 100%;
text-align: center;
height: 20px;
line-height: 20px;
}
}
.upload-warp {
@utils-clearfix;
.upload-btn,.upload-cancel {
float: left;
display:inline-block;
width: 60px;
height: 25px;
line-height: 25px;
color: #fff;
border-radius: 5px;
background: #49a9ee;
box-shadow: 0 0 0 #333;
text-align: center;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
cursor: pointer;
margin-top: 5px;
}
.upload-cancel{
background: gray;
float: right;
}
}
.to-send-file {
margin-top: 5px;
display: block;
width: 50px;
height: 25px;
line-height: 25px;
color: #fff;
border-radius: 5px;
background: #49a9ee;
cursor: pointer;
}
}
}
</style>
vue 实现 裁切图片 同时有放大、缩小、旋转功能的更多相关文章
- 制作一个顶部图片可以拉伸放大缩小效果的tableViewHeader
最近负责公司项目个人中心的项目模块研发,首页是一个头部图片可以拉伸放大缩小效果的tableViewHeader,今天这个demo和教程我增加了模糊效果和头像缩小效果.具体效果如图: 如果这个效果是想要 ...
- WPF多点触摸放大缩小旋转
原文:WPF多点触摸放大缩小旋转 版权声明:本文为博主原创文章,需要转载尽管转载. https://blog.csdn.net/z5976749/article/details/40118437 如果 ...
- JS控制图片拖动 放大 缩小 旋转 支持滚轮放大缩小 IE有效
<html> <head> <title>图片拖动,放大,缩小,转向</title> <script type="text/ja ...
- canvas上画出坐标集合,并标记新坐标,背景支持放大缩小拖动功能
写在前面:项目需求,用户上传一个区位的平面图片,用户可以在图片上添加新的相机位置,并且展示之前已绑定的相机坐标位置,图片支持放大缩小&拖动的功能.新增坐标,页面展示相对canvas定位,保存时 ...
- 猫猫学IOS(二)UI之button操作 点击变换 移动 放大缩小 旋转
不多说,先上图片看效果,猫猫分享.必须精品 原创文章.欢迎转载.转载请注明:翟乃玉的博客 地址:viewmode=contents">http://blog.csdn.net/u013 ...
- AJ学IOS(02)UI之按钮操作 点击变换 移动 放大缩小 旋转
不多说,先上图片看效果,AJ分享,必须精品 这个小程序主要实现点击方向键可以让图标上下左右动还有放大缩小以及旋转的功能,点击图片会显示另一张图片. 点击变换 其实用到了按钮的两个状态,再State C ...
- 【VUE】图片预览放大缩小插件
From: https://www.jianshu.com/p/e3350aa1b0d0 在看项目时,突然看到预览图片的弹窗,感觉好僵硬,不能放大,不能切换,于是便在网上找下关于图片预览的插件,有找到 ...
- 手动实现图片预览-放大缩小全屏支持IE9以上
#{extends '/Index/index.html' /} #{set title:'意见反馈' /} <script src="/public/mgr/javascripts/ ...
- Winform 图片鼠标滚动查看(放大,缩小,旋转,拖动查看)[日常随笔]
方法千千万,我只是其中一笔[通过控制PictureBox来控制图片,图片完全施展在控件中]...几久不做,还真有点陌生! 窗体构造中添加鼠标滚动: /// <summary> /// 窗体 ...
随机推荐
- python学习笔记(15)pymysql数据库操作
pymysql数据库操作 1.什么是PyMySQL 为了使python连接上数据库,你需要一个驱动,这个驱动是用于与数据库交互的库. PyMySQL : 这是一个使Python连接到MySQL的库,它 ...
- [LC] 15. 3Sum
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find ...
- ReentrantLock(重入锁)的源码解析
转自:从源码角度彻底理解ReentrantLock(重入锁)](https://www.cnblogs.com/takumicx/p/9402021.html)) 公平锁内部是FairSync,非公平 ...
- 浏览器证书问题,chorm,ie,edge,safari都会去读系统证书,firefox例外
坑爹 没想过浏览器兼容的问题. 为系统安装用户证书后, firefox一直无法连接 提示 连接 www.httpsserver.com:8985 时发生错误. SSL 对等端无法协商出一个可接受的安全 ...
- navisworks安装未完成,某些产品无法安装的解决方法
navisworks提示安装未完成,某些产品无法安装该怎样解决呢?,一些朋友在win7或者win10系统下安装navisworks失败提示navisworks安装未完成,某些产品无法安装,也有时候想重 ...
- MYSQL语句中的explain
1.使用mysql explain的原因 在我们程序员的日常写代码中,有时候会发现我们写的sql语句运行的特别慢,导致响应时间特别长,这种情况在高并发的情况下,我们的网站会直接崩溃,为什么双十一的淘宝 ...
- Linux下文件 ~/.bashrc 和 ~/.bash_profile 和 /etc/bashrc 和 /etc/profile 的区别 | 用户登录后加载配置文件的顺序
转自 https://blog.csdn.net/secondjanuary/article/details/9206151 文件说明: /ect/profile 此文件为系统的每个用户设置环境信息, ...
- python3下应用requests
模拟浏览器请求有两种,一种是不需要用户登录或者验证的请求,一种是需要用户登录或者验证的请求 那么我们先来说说不需要用户登录的方法 这种方式直接可以获取源码,用get的请求方式 登录的方式 获取这种页面 ...
- 思科WLC5508上传定制Portal展示模版
1. 登录Cisco设备,获取模板样例登录cisco WLC设备后点击help,打开帮助文档Wireless Tab-->Web Login Page-->External Web Aut ...
- MyBatis if test 传入一个数字进行比较报错 There is no getter for property named 'userState' in 'class java.lang.Integer'
在写MyBatis映射文件中,我要传入一个 int 类型的参数,在映射文件中用 'test' 中进行比较,我花了很长时间百度,发现都是不靠谱的方法,有把数字在比较时转成字符串用 equals 比较的. ...