本文将介绍基于Angular的图片裁剪上传插件。
github: https://github.com/licaomeng/angular-image-upload
希望大家帮忙Star一下我的项目,我会持续更新~O(∩_∩)O
插件效果如下:
该插件的图片裁剪是通过图片的放大、缩小、拖动完成的。而不同于我们通常所见到的拖动剪裁范围,进行的图片剪裁。这是一种反向思维。
imgZoomCanvas.js
图片的放大、缩小、拖动,全部是在html5的Canvas上面完成的。实现该算法的核心代码封装在 imgZoomCanvas.js 里面。
/**
* Created by Caomeng Li on 8/23/2016.
*/
angular.module('appModule')
.factory('imgZoomCanvas', [function () {
//singleton
var INSTANCE = null;
var getInstance = function (options) {
return INSTANCE || ( INSTANCE = new CanvasZoom(options) );
}
var destroyInstance = function () {
if (INSTANCE) {
INSTANCE = null;
}
}
var stopAnimate = function () {
return INSTANCE ? INSTANCE.stopAnimate() : null;
}
var onZoom = function (zoom) {
return INSTANCE ? INSTANCE.doZoom(zoom) : null;
}
var CanvasZoom = function (options) {
if (!options || !options.canvas) {
throw 'CanvasZoom constructor: missing arguments canvas';
}
if (!options.image) {
throw 'CanvasZoom constructor: missing arguments image';
}
this.canvas = options.canvas;
this.image = options.image;
this.currentAnimationId = 0;
this.canvas.width = this.canvas.clientWidth;
this.canvas.height = this.canvas.clientHeight;
this.context = this.canvas.getContext('2d');
this.lastX = 0;
this.lastY = 0;
this.position = {
x: 0,
y: 0
};
this.initPosition = {
x: 0,
y: 0
}
this.scale = {
x: 1,
y: 1
};
this.initScale = {
x: 1,
y: 1
};
this.init = false;
this.checkRequestAnimationFrame();
this.currentAnimationId = requestAnimationFrame(this.animate.bind(this));
this.setEventListeners();
}
CanvasZoom.prototype = {
stopAnimate: function () {
cancelAnimationFrame(this.currentAnimationId);
},
animate: function () {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
v