使用JavaScript+canvas实现图片裁剪_jquery

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;
}

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

时间: 2024-09-30 10:17:37

使用JavaScript+canvas实现图片裁剪_jquery的相关文章

javascript canvas给图片加水印

[.设置图片 .水印内容   ].效果 加阴影  字体颜色  黑色灰色蓝色黄色绿色紫色 字体名称  宋体黑体微软雅黑Arial 字体大小  12px13px14px15px16px17px18px 坐标: X-;Y-   字体样式  正常斜体 您的浏览器不支持Canvas,请升级浏览器到最新版本再尝试 以上是小编为您精心准备的的内容,在的博客.问答.公众号.人物.课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索浏览器 canvas html5 canvas图片水印.canvas给图片

javascript 图片裁剪技巧

学php gd库 看到有图片裁剪 正好整一个 嗯 其实挺简单的 php版,代码如下: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Resize&l

jquery.Jcrop结合JAVA后台实现图片裁剪上传实例_jquery

本文介绍了头像裁剪上传功能,用到的技术有  jQuery,springmvc,裁剪插件用的是jcrop(中间遇到很多坑,最终跨越). 图片上传步骤: 1.用户选择图片 2.将图片传入后台:用户选择图片的时候选择的是各种各样的,但是我们的网页显示图片大小是有限的,所以我们就要在用户选择图片之后将图片添加到后台进行压缩,压缩成我们想要的大小,之后再显示到页面才好 3.利用jcrop裁剪工具对图片进行裁剪并且实时预览 4.点击确定按钮将裁剪用到的参数传入后台,后台图片进行剪切,之后缩放成我们需要的格式

javascript 图片裁剪技巧解读_javascript技巧

学php gd库 看到有图片裁剪 正好整一个 嗯 其实挺简单的 php版 复制代码 代码如下: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Res

javascript结合canvas实现图片旋转效果_javascript技巧

我们在微博上可以对图片进行向左转向右转等旋转操作,让用户可以从不同的视角欣赏图片效果.本文将结合实例为您讲解如何使用Javascript结合相关技术来实现图片的旋转效果.我们使用HTML5的canvas标签可对图片进行旋转操作,对于ie6,7,8不支持HTML5的浏览器,我们使用IE特有的滤镜效果来实现图片旋转. HTML 我们在页面中放置一张图片,在图片的上方放置两个按钮,通过onclick事件调用rotate()函数来控制图片向左向右旋转. <div id="tool">

图片保存-win8 javascript canvas开发

问题描述 win8 javascript canvas开发 win8提供的利用winjs的开发方式中可以使用html5种的canvas,但是如何将我的cavas中绘制的图形保存起来呢,据我了解是不可以实现的.那么这种需求要怎么做呢,在线等,急,求各路朋友们一起讨论一下

javascript转换静态图片,增加粒子动画效果

  这篇文章主要介绍了javascript转换静态图片,增加粒子动画效果,非常的炫酷,需要的朋友可以参考下 使用getImageData接口获取图片的像素点,然后基于像素点实现动画效果,封装成一个简单的lib ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 <!DOCTYPE html> <html> <head> <title>particle image<

Android实现相机拍摄、选择、图片裁剪功能_Android

最近的一些学习心得: 功能实现:点击圆形头像之后可以实现相册上传或者开启相机,然后把得到的图片经过剪裁,把剪裁过的图片设置为头像的背景图 步骤:第一步:自定义一个类,继承ImageView,重写draw方法,实现外观为圆形 第二步:在xml文件中引用该控件 第三步:实现圆形头像的点击事件,点击后显示对话框界面,询问你是打开相册还是相机(自动省略显示对话框的代码) 第四步:根据用户选择情况,打开相册或者相机 第五步:将拍摄的图片或者相册选中的图片进行剪裁,将结果保存在指定内存区域 第六步:更新头像

使用JCrop进行图片裁剪,裁剪js说明,裁剪预览,裁剪上传,裁剪设计的图片处理的工具类和代码

 1.要想制作图片裁剪功能,可以使用网上的裁剪工具JCrop,网址是:https://github.com/tapmodo/Jcrop/ 案例效果如下: 2.引入JCrop的js代码,具体要引入那些js可以参考JCrop案例: 3.编写的html代码如下: <div id="light" class="white_content">        <div class="vatitlee">            封面