使用JavaScript+canvas实现图片裁剪


Posted in Javascript onJanuary 30, 2015

canvas是一个可以让我们使用脚本绘图的标签,它提供了一系列完整的属性和方法。我们可以借此来实现图形绘制,图像处理甚至实现简单的动画和游戏制作。

canvas标签只有两个属性:width和height,用来设定画布的宽和高,如果没有通过标签属性或者脚本来设置,默认为300*150;

好了,canvas的介绍就先到这里,下面我们来看看javascript结合canvas实现图片的裁剪代码:

var selectObj = null;

function ImageCrop(canvasId, imageSource, x, y, width, height) {

    var canvas = $("#" + canvasId);

    if (canvas.length == 0 && imageSource) {

        return;

    }

    function canvasMouseDown(e) {

        StopSelect(e);

        canvas.css("cursor", "default");

    }

    function canvasMouseMove(e) {

        var canvasOffset = canvas.offset();

        var pageX = e.pageX || event.targetTouches[0].pageX;

        var pageY = e.pageY || event.targetTouches[0].pageY;

        iMouseX = Math.floor(pageX - canvasOffset.left);

        iMouseY = Math.floor(pageY - canvasOffset.top);

        canvas.css("cursor", "default");

        if (selectObj.bDragAll) {

            canvas.css("cursor", "move");

            canvas.data("drag", true);

            var cx = iMouseX - selectObj.px;

            cx = cx < 0 ? 0 : cx;

            mx = ctx.canvas.width - selectObj.w;

            cx = cx > mx ? mx : cx;

            selectObj.x = cx;

            var cy = iMouseY - selectObj.py;

            cy = cy < 0 ? 0 : cy;

            my = ctx.canvas.height - selectObj.h;

            cy = cy > my ? my : cy;

            selectObj.y = cy;

        }

        for (var i = 0; i < 4; i++) {

            selectObj.bHow[i] = false;

            selectObj.iCSize[i] = selectObj.csize;

        }

        // hovering over resize cubes

        if (iMouseX > selectObj.x - selectObj.csizeh && iMouseX < selectObj.x + selectObj.csizeh &&

            iMouseY > selectObj.y - selectObj.csizeh && iMouseY < selectObj.y + selectObj.csizeh) {

            canvas.css("cursor", "pointer");

            selectObj.bHow[0] = true;

            selectObj.iCSize[0] = selectObj.csizeh;

        }

        if (iMouseX > selectObj.x + selectObj.w - selectObj.csizeh && iMouseX < selectObj.x + selectObj.w + selectObj.csizeh &&

            iMouseY > selectObj.y - selectObj.csizeh && iMouseY < selectObj.y + selectObj.csizeh) {

            canvas.css("cursor", "pointer");

            selectObj.bHow[1] = true;

            selectObj.iCSize[1] = selectObj.csizeh;

        }

        if (iMouseX > selectObj.x + selectObj.w - selectObj.csizeh && iMouseX < selectObj.x + selectObj.w + selectObj.csizeh &&

            iMouseY > selectObj.y + selectObj.h - selectObj.csizeh && iMouseY < selectObj.y + selectObj.h + selectObj.csizeh) {

            canvas.css("cursor", "pointer");

            selectObj.bHow[2] = true;

            selectObj.iCSize[2] = selectObj.csizeh;

        }

        if (iMouseX > selectObj.x - selectObj.csizeh && iMouseX < selectObj.x + selectObj.csizeh &&

            iMouseY > selectObj.y + selectObj.h - selectObj.csizeh && iMouseY < selectObj.y + selectObj.h + selectObj.csizeh) {

            canvas.css("cursor", "pointer");

            selectObj.bHow[3] = true;

            selectObj.iCSize[3] = selectObj.csizeh;

        }

        if (iMouseX > selectObj.x && iMouseX < selectObj.x + selectObj.w && iMouseY > selectObj.y && iMouseY < selectObj.y + selectObj.h) {

            canvas.css("cursor", "move");

        }

        // in case of dragging of resize cubes

        var iFW, iFH, iFX, iFY, mx, my;

        if (selectObj.bDrag[0]) {

            iFX = iMouseX - selectObj.px;

            iFY = iMouseY - selectObj.py;

            iFW = selectObj.w + selectObj.x - iFX;

            iFH = selectObj.h + selectObj.y - iFY;

            canvas.data("drag", true);

        }

        if (selectObj.bDrag[1]) {

            iFX = selectObj.x;

            iFY = iMouseY - selectObj.py;

            iFW = iMouseX - selectObj.px - iFX;

            iFH = selectObj.h + selectObj.y - iFY;

            canvas.data("drag", true);

        }

        if (selectObj.bDrag[2]) {

            iFX = selectObj.x;

            iFY = selectObj.y;

            iFW = iMouseX - selectObj.px - iFX;

            iFH = iMouseY - selectObj.py - iFY;

            canvas.data("drag", true);

        }

        if (selectObj.bDrag[3]) {

            iFX = iMouseX - selectObj.px;

            iFY = selectObj.y;

            iFW = selectObj.w + selectObj.x - iFX;

            iFH = iMouseY - selectObj.py - iFY;

            canvas.data("drag", true);

        }

        if (iFW > selectObj.csizeh * 2 && iFH > selectObj.csizeh * 2) {

            selectObj.w = iFW;

            selectObj.h = iFH;

            selectObj.x = iFX;

            selectObj.y = iFY;

        }

        drawScene();

    }

    function canvasMouseOut() {

        $(canvas).trigger("mouseup");

    }

    function canvasMouseUp() {

        selectObj.bDragAll = false;

        for (var i = 0; i < 4; i++) {

            selectObj.bDrag[i] = false;

        }

        canvas.css("cursor", "default");

        canvas.data("select", {

            x: selectObj.x,

            y: selectObj.y,

            w: selectObj.w,

            h: selectObj.h

        });

        selectObj.px = 0;

        selectObj.py = 0;

    }

    function Selection(x, y, w, h) {

        this.x = x; // initial positions

        this.y = y;

        this.w = w; // and size

        this.h = h;

        this.px = x; // extra variables to dragging calculations

        this.py = y;

        this.csize = 4; // resize cubes size

        this.csizeh = 6; // resize cubes size (on hover)

        this.bHow = [false, false, false, false]; // hover statuses

        this.iCSize = [this.csize, this.csize, this.csize, this.csize]; // resize cubes sizes

        this.bDrag = [false, false, false, false]; // drag statuses

        this.bDragAll = false; // drag whole selection

    }

    Selection.prototype.draw = function () {

        ctx.strokeStyle = '#666';

        ctx.lineWidth = 2;

        ctx.strokeRect(this.x, this.y, this.w, this.h);

        // draw part of original image

        if (this.w > 0 && this.h > 0) {

            ctx.drawImage(image, this.x, this.y, this.w, this.h, this.x, this.y, this.w, this.h);

        }

        // draw resize cubes

        ctx.fillStyle = '#999';

        ctx.fillRect(this.x - this.iCSize[0], this.y - this.iCSize[0], this.iCSize[0] * 2, this.iCSize[0] * 2);

        ctx.fillRect(this.x + this.w - this.iCSize[1], this.y - this.iCSize[1], this.iCSize[1] * 2, this.iCSize[1] * 2);

        ctx.fillRect(this.x + this.w - this.iCSize[2], this.y + this.h - this.iCSize[2], this.iCSize[2] * 2, this.iCSize[2] * 2);

        ctx.fillRect(this.x - this.iCSize[3], this.y + this.h - this.iCSize[3], this.iCSize[3] * 2, this.iCSize[3] * 2);

    };

    var drawScene = function () {

        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); // clear canvas

        // draw source image

        ctx.drawImage(image, 0, 0, ctx.canvas.width, ctx.canvas.height);

        // and make it darker

        ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';

        ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);

        // draw selection

        selectObj.draw();

        canvas.mousedown(canvasMouseDown);

        canvas.on("touchstart", canvasMouseDown);

    };

    var createSelection = function (x, y, width, height) {

        var content = $("#imagePreview");

        x = x || Math.ceil((content.width() - width) / 2);

        y = y || Math.ceil((content.height() - height) / 2);

        return new Selection(x, y, width, height);

    };

    var ctx = canvas[0].getContext("2d");

    var iMouseX = 1;

    var iMouseY = 1;

    var image = new Image();

    image.onload = function () {

        selectObj = createSelection(x, y, width, height);

        canvas.data("select", {

            x: selectObj.x,

            y: selectObj.y,

            w: selectObj.w,

            h: selectObj.h

        });

        drawScene();

    };

    image.src = imageSource;

    canvas.mousemove(canvasMouseMove);

    canvas.on("touchmove", canvasMouseMove);

    var StopSelect = function (e) {

        var canvasOffset = $(canvas).offset();

        var pageX = e.pageX || event.targetTouches[0].pageX;

        var pageY = e.pageY || event.targetTouches[0].pageY;

        iMouseX = Math.floor(pageX - canvasOffset.left);

        iMouseY = Math.floor(pageY - canvasOffset.top);

        selectObj.px = iMouseX - selectObj.x;

        selectObj.py = iMouseY - selectObj.y;

        if (selectObj.bHow[0]) {

            selectObj.px = iMouseX - selectObj.x;

            selectObj.py = iMouseY - selectObj.y;

        }

        if (selectObj.bHow[1]) {

            selectObj.px = iMouseX - selectObj.x - selectObj.w;

            selectObj.py = iMouseY - selectObj.y;

        }

        if (selectObj.bHow[2]) {

            selectObj.px = iMouseX - selectObj.x - selectObj.w;

            selectObj.py = iMouseY - selectObj.y - selectObj.h;

        }

        if (selectObj.bHow[3]) {

            selectObj.px = iMouseX - selectObj.x;

            selectObj.py = iMouseY - selectObj.y - selectObj.h;

        }

        if (iMouseX > selectObj.x + selectObj.csizeh &&

            iMouseX < selectObj.x + selectObj.w - selectObj.csizeh &&

            iMouseY > selectObj.y + selectObj.csizeh &&

            iMouseY < selectObj.y + selectObj.h - selectObj.csizeh) {

            selectObj.bDragAll = true;

        }

        for (var i = 0; i < 4; i++) {

            if (selectObj.bHow[i]) {

                selectObj.bDrag[i] = true;

            }

        }

    };

    canvas.mouseout(canvasMouseOut);

    canvas.mouseup(canvasMouseUp);

    canvas.on("touchend", canvasMouseUp);

    this.getImageData = function (previewID) {

        var tmpCanvas = $("<canvas></canvas>")[0];

        var tmpCtx = tmpCanvas.getContext("2d");

        if (tmpCanvas && selectObj) {

            tmpCanvas.width = selectObj.w;

            tmpCanvas.height = selectObj.h;

            tmpCtx.drawImage(image, selectObj.x, selectObj.y, selectObj.w, selectObj.h, 0, 0, selectObj.w, selectObj.h);

            if (document.getElementById(previewID)) {

                document.getElementById(previewID).src = tmpCanvas.toDataURL();

                document.getElementById(previewID).style.border = "1px solid #ccc";

            }

            return tmpCanvas.toDataURL();

        }

    };

}

function autoResizeImage(maxWidth, maxHeight, objImg) {

    var img = new Image();

    img.src = objImg.src;

    var hRatio;

    var wRatio;

    var ratio = 1;

    var w = objImg.width;

    var h = objImg.height;

    wRatio = maxWidth / w;

    hRatio = maxHeight / h;

    if (w < maxWidth && h < maxHeight) {

        return;

    }

    if (maxWidth == 0 && maxHeight == 0) {

        ratio = 1;

    } else if (maxWidth == 0) {

        if (hRatio < 1) {

            ratio = hRatio;

        }

    } else if (maxHeight == 0) {

        if (wRatio < 1) {

            ratio = wRatio;

        }

    } else if (wRatio < 1 || hRatio < 1) {

        ratio = (wRatio <= hRatio ? wRatio : hRatio);

    } else {

        ratio = (wRatio <= hRatio ? wRatio : hRatio) - Math.floor(wRatio <= hRatio ? wRatio : hRatio);

    }

    if (ratio < 1) {

        if (ratio < 0.5 && w < maxWidth && h < maxHeight) {

            ratio = 1 - ratio;

        }

        w = w * ratio;

        h = h * ratio;

    }

    objImg.height = h;

    objImg.width = w;

}

小伙伴们拿去试试吧,希望大家能够喜欢,有疑问就给我留言吧。

Javascript 相关文章推荐
js CSS操作方法集合
Oct 31 Javascript
Prototype 学习 工具函数学习($w,$F方法)
Jul 12 Javascript
javascript判断ie浏览器6/7版本加载不同样式表的实现代码
Dec 26 Javascript
js实现div的切换特效上一个下一个
Feb 11 Javascript
详解如何较好的使用js
Dec 16 Javascript
js数字计算 误差问题的快速解决方法
Feb 28 Javascript
JavaScript实现二维坐标点排序效果
Jul 18 Javascript
react build 后打包发布总结
Aug 24 Javascript
详解webpack引用jquery(第三方模块)的三种办法
Aug 21 jQuery
jQuery利用cookie 实现本地收藏功能(不重复无需多次命名)
Nov 07 jQuery
vue 中 get / delete 传递数组参数方法
Mar 23 Vue.js
vue使用echarts实现折线图
Mar 21 Vue.js
js判断手机和pc端选择不同执行事件的方法
Jan 30 #Javascript
项目中常用的JS方法整理
Jan 30 #Javascript
jQuery实现带滚动线条导航效果的方法
Jan 30 #Javascript
jquery实现拖拽调整Div大小
Jan 30 #Javascript
jQuery中$.click()无效问题分析
Jan 29 #Javascript
Eclipse配置Javascript开发环境图文教程
Jan 29 #Javascript
js操作滚动条事件实例
Jan 29 #Javascript
You might like
php之CodeIgniter学习笔记
2013/06/17 PHP
php实现天干地支计算器示例
2014/03/14 PHP
PHP的mysqli_select_db()函数讲解
2019/01/23 PHP
tp5框架基于Ajax实现列表无刷新排序功能示例
2020/02/10 PHP
YII2框架中actions的作用与使用方法示例
2020/03/13 PHP
php设计模式之原型模式分析【星际争霸游戏案例】
2020/03/23 PHP
PHP常用字符串输出方法分析(echo,print,printf及sprintf)
2021/03/09 PHP
一个无限级XML绑定跨框架菜单(For IE)
2007/01/27 Javascript
JavaScript中将一个值转换为字符串的方法分析[译]
2012/09/21 Javascript
JavaScript加强之自定义callback示例
2013/09/21 Javascript
jQuery动态创建html元素的常用方法汇总
2014/09/05 Javascript
JS控制表格实现一条光线流动分割行的方法
2015/03/09 Javascript
javascript框架设计之类工厂
2015/06/23 Javascript
jQuery实现类似标签风格的导航菜单效果代码
2015/08/25 Javascript
JS提示:Uncaught SyntaxError:Unexpected token ) 错误的解决方法
2016/08/19 Javascript
chrome下判断点击input上标签还是其余标签的实现方法
2016/09/18 Javascript
jquery实现侧边栏左右伸缩效果的示例
2017/12/19 jQuery
微信小程序事件对象中e.target和e.currentTarget的区别详解
2019/05/08 Javascript
安装多版本Vue-CLI的实现方法
2020/03/24 Javascript
JavaScript this关键字的深入详解
2021/01/14 Javascript
[00:35]TI7不朽珍藏III——寒冰飞龙不朽展示
2017/07/15 DOTA
Python中的高级函数map/reduce使用实例
2015/04/13 Python
python操作字典类型的常用方法(推荐)
2016/05/16 Python
Python3实现简单可学习的手写体识别(实例讲解)
2017/10/21 Python
python多个模块py文件的数据共享实例
2019/01/11 Python
django 中的聚合函数,分组函数,F 查询,Q查询
2019/07/25 Python
python被修饰的函数消失问题解决(基于wraps函数)
2019/11/04 Python
全网最全python库selenium自动化使用详细教程
2021/01/12 Python
配置H5的滚动条样式的示例代码
2018/03/09 HTML / CSS
美国网上订购鲜花:FTD
2016/09/23 全球购物
日本订房网站,预订日本星级酒店/温泉旅馆:Relux(支持中文)
2020/01/03 全球购物
物业招聘计划书
2014/01/10 职场文书
家长对孩子评语
2014/01/30 职场文书
党的群众路线教育实践活动个人整改方案
2014/09/21 职场文书
大专护理专业自荐信
2015/03/25 职场文书
python 算法题——快乐数的多种解法
2021/05/27 Python