html canvas[autodyne] image clipping

html:

<div class="upload" id="head_up" style="display: none">
        <p class="p-2">
            <i class="i-1"></i>上传头像<i class="i-2" id="exitHeadImgUpload"></i>
        </p>
        <div class="left pull-left">
            <input id="lefile" type="file" style="display: none" />
            <button type="button" class="btn btn1"
                onclick="$('input[id=lefile]').click();">
                <i class="i-3"></i>选择照片
            </button>
            <button type="button" class="btn btn2" id="autodyne">
                <i class="i-4"></i>自拍头像
            </button>
            <div class="p-1">
                <canvas id="headImgCanvas" height="235px;" width="235px"
                    style="position: absolute;margin-left:10px;margin-top:7px;display:none">your
                of the browser not support canvas.</canvas>
                <canvas
                    style="position: absolute;margin-left:10px;margin-top:7px;display:none"
                    id="headImgPhotoCanvas" height="235px;" width="235px">your
                of the browser not support canvas.</canvas>
                <video id="headImgVideo" height="235px;" width="335px"
                    controls="controls" autoplay="autoplay" style="display:none"></video>
            </div>
            <div class="row">
                <div class="col-sm-offset-1">
                    <button type="button" class="btn btn3" id="headImgPhoto">拍照</button>
                    <button type="button" class="btn btn3" id="headImgClipping">剪裁</button>
                    <!--                    <button type="button" class="btn btn3">重新选择</button> -->
                    <button type="button" class="btn btn4" id="headImgSubmit">上传</button>
                </div>
            </div>
        </div>
        <div class="right pull-left">
            <p class="red">预览效果 :</p>
            <div class="xiaotu">
                <img id="headImgMin" height="60" width="60" />
            </div>
            <p class="p-4">60x60</p>
            <div class="datu">
                <img id="headImgMax" height="146" width="146" />
            </div>
            <p class="p-4">146x146</p>
        </div>
    </div>
css:

*{
    margin:0;
    padding:0;
    box-sizing:border-box;
    list-style:none;
}
body {
    font-size:16px;
    font-family:Arial,Verdana;
    color:#666;
    font-family: "SimHei", "Helvetica Neue";
}
.main{
    background:purple;
    position:relative;
    width:1170px;
    height:1000px;
}
.upload{
    position:absolute;
    height:442px;
    width:640px;
    background-color:#f0f0f0;
    left:50%;
    top:50%;
    margin-left:-320px;
    margin-top:-211px;
    border-radius:5px;
    overflow:hidden;
}
.p-2{
    background:#e5e4e4;
    height:45px;
    line-height:45px;
}
.i-1{
    display:inline-block;
    width:19px;
    height:22px;
    background:url(../../imgs/head_img_upload/list.png) no-repeat;
    margin:10px;
    vertical-align:top;
}
.i-2{
    float:right;
    height:30px;
    width:30px;
    background:url(../../imgs/head_img_upload/list.png) 0 -22px no-repeat;
    margin-top:6px;
    margin-right:6px;
}
.btn1,.btn2{
    font-size:18px;
    line-height:30px;
    border:1px solid #cacaca;
}
.btn1{
    background:#55b8ed;
    color:#fff;
}
.btn2{
    background:#f0f0f0;
}
.i-3{
    display:inline-block;
    width:20px;
    height:18px;
    background:url(../../imgs/head_img_upload/list.png) -22px 0 no-repeat;
    vertical-align:top;
    margin-top:5px;
}
.i-4{
    display:inline-block;
    width:20px;
    height:20px;
    background:url(../../imgs/head_img_upload/list.png) -43px 0 no-repeat;
    vertical-align:top;
    margin-top:4px;
}
.p-1{
    width:257px;
    height:250px;
    margin-top:20px;
    margin-bottom:16px;
}
.btn3,.btn4{
    width:99px;
    height:36px;
    color:#fff;
    font-size:18px;
}
.btn4{
    background:#fe4f4f;
}
.left{
    width:409px;
    padding:23px;
}
.upload .right{
    padding:13px;
    width:231px;
}
.red{
    color:#fe4f4f;
}
.xiaotu{
    width:60px;
    height:60px;
    margin:10px auto;
}
.p-4{
    height:40px;
    text-align:center;
    color:#b7b7b7;
}
.datu{
    width:146px;
    height:146px;
    margin:10px auto;
}
js:

$(function() {
    /*
     * 
     * 
     */
    $("#lefile").change(function(e) {
        console.log($("#lefile").val());
        var headImgPhotoCanvas = document.getElementById("headImgPhotoCanvas");
        var headImgPhotoContext = headImgPhotoCanvas.getContext("2d");
        var image = new Image();
        image.src = $("#lefile").val();
        headImgPhotoContext.drawImage(image, 0, 0, 235, 235);
    });///
    /*
     * 
     */
    $("#exitHeadImgUpload").click(function(e) {
        $("#head_up").trigger('close');
    });
    /*
     * Autodyne picture. get user media. set video src of the local mdeida
     * stream. video add event play let canvas draw image data /20 s. video add
     * event pause ... clear interval. video add event ended ... clear interval.
     */
    $("#autodyne")
            .click(
                    function(e) {
                        $("#headImgCanvas").css("display", "block");
                        $("#headImgPhotoCanvas").css("display", "none");
                        var canvas = document.getElementById("headImgCanvas");
                        var context = canvas.getContext("2d");
                        var video = document.getElementById("headImgVideo");
                        var getUserMedia = (navigator.getUserMedia
                                || navigator.webkitGetUserMedia
                                || navigator.mozGetUserMedia || navigator.msGetUserMedia);
                        getUserMedia.call(navigator, {
                            video : true,
                            audio : false
                        },
                                function(localMediaStream) {
                                    video.src = window.URL
                                            .createObjectURL(localMediaStream);
                                    video.onloadedmetadata = function(e2) {
                                        console.log("Label: "
                                                + localMediaStream.label);
                                        console.log("AudioTracks",
                                                localMediaStream
                                                        .getAudioTracks());
                                        console.log("VideoTracks",
                                                localMediaStream
                                                        .getVideoTracks());
                                    };
                                }, function(e1) {
                                    console.log('Reeeejected!', e1);
                                });
                        video.addEventListener("play", function() {
                            var i = window.setInterval(function() {
                                context.drawImage(video, 0, 0, 235, 235)
                            }, 20);
                        }, false);
                        video.addEventListener('pause', function() {
                            window.clearInterval(i);
                        }, false);
                        video.addEventListener('ended', function() {
                            clearInterval(i);
                        }, false);
                    });

    var headImgCanvas = document.getElementById("headImgCanvas");
    var headImgContext = headImgCanvas.getContext("2d");
    var headImgPhotoCanvas = document.getElementById("headImgPhotoCanvas");
    var headImgPhotoContext = headImgPhotoCanvas.getContext("2d");
    var headImgData;
    /*
     * complete photo work.
     */
    $("#headImgPhoto").click(function(e) {
        $("#headImgCanvas").css("display", "none");
        $("#headImgPhotoCanvas").css("display", "block");
        headImgData = headImgContext.getImageData(0, 0, 235, 235);
        headImgPhotoContext.putImageData(headImgData, 0, 0, 0, 0, 235, 235);
        setStrokeStyleGradient(headImgPhotoContext);
        headImgPhotoContext.lineWidth = 0.8;
        headImgPhotoContext.strokeRect(45, 45, 146, 146);
    });

    /*
     * set stroke style gradient.
     */
    function setStrokeStyleGradient(ctx) {
        var gradient = ctx.createLinearGradient(0, 0, 170, 0);
        gradient.addColorStop("0", "magenta");
        gradient.addColorStop("0.5", "blue");
        gradient.addColorStop("1.0", "red");
        ctx.strokeStyle = gradient;
    }

    // first position value.
    var centerPosition = null;

    /*
     * when mouse trigger mousedown add event mousemove. let rect move. move
     * before erasure path trace. and record first position value.
     */
    headImgPhotoCanvas.addEventListener('mousedown', function(e) {
        centerPosition = getMousePos(headImgPhotoCanvas, e);
        headImgPhotoCanvas.addEventListener('mousemove', mobileRectangular,
                false);
    }, false);
    /*
     * when mouse trigger mouseup remove event mousemove. let rect not move. and
     * record next ultimately position value.
     */
    headImgPhotoCanvas.addEventListener('mouseup', function(e) {
        if (headImgPhotoCanvas.removeEventListener) { // All browsers, in
            // addition to IE 8 and
            // the earlier version
            // of IE
            headImgPhotoCanvas.removeEventListener("mousemove",
                    mobileRectangular, false);
        } else if (headImgPhotoCanvas.detachEvent) { // IE 8 and IE version
            // earlier
            headImgPhotoCanvas.detachEvent('onmousemove', mobileRectangular,
                    false);
        }
    }, false);
    // ultimately position value.
    var position = null;

    var left_top_x = 45;
    var left_top_y = 45;
    var rect_width = 146;
    var rect_height = 146;
    /*
     * when mouse mousemove trigger of the event. towards canvas put image data.
     * complete photo work. towards canvas set stroke style gradient. calculate
     * rect position let rect follow mouse walk about.
     */
    function mobileRectangular(e) {
        headImgPhotoCanvas.setAttribute("height", 235);
        headImgPhotoCanvas.setAttribute("width", 235);

        position = getMousePos(headImgPhotoCanvas, e);
        headImgPhotoContext.putImageData(headImgData, 0, 0, 0, 0, 235, 235);
        setStrokeStyleGradient(headImgPhotoContext);
        // control rect move.
        left_top_x = (45 + (position.x - centerPosition.x));
        left_top_y = (45 + (position.y - centerPosition.y));

        /*
         * impose restrictions on rect no move out left and top boundary.
         */
        if (left_top_x < 0) {
            left_top_x = 1;
        }

        if (left_top_y < 0) {
            left_top_y = 1;
        }

        /*
         * impose restrictions on rect no move out right and bottom boundary.
         */
        if ((234 - left_top_x) < 146) {
            left_top_x = 234 - 146;
        }

        if ((233 - left_top_y) < 146) {
            left_top_y = 233 - 146;
        }

        headImgPhotoContext.strokeRect(left_top_x, left_top_y, 146, 146);
    }

    var imagebase = null;

    /*
     * clipping photo data. not clipping gradient. put a new of the canvas. put
     * before save of the image data. last complete let canvas convert by
     * image/png/base64 coding.
     */
    $("#headImgClipping").click(
            function(e) {
                var headImgPhotoClippingData = headImgPhotoContext
                        .getImageData(left_top_x + 1, left_top_y + 1,
                                rect_width - 2, rect_height - 2);
                headImgPhotoCanvas.setAttribute("height", rect_height - 2);
                headImgPhotoCanvas.setAttribute("width", rect_width - 2);
                headImgPhotoContext.putImageData(headImgPhotoContext
                        .createImageData(235, 235), 0, 0, 0, 0, 235, 235);
                headImgPhotoContext.putImageData(headImgPhotoClippingData, 0,
                        0, 0, 0, 235, 235);
                imagebase = headImgPhotoCanvas.toDataURL("image/png");
                $("#headImgMin").attr("src", imagebase);
                $("#headImgMax").attr("src", imagebase);
            });

    $("#headImgSubmit").click(function(e) {
        $.post("personalCenter/changeHeadImg", {
            "headImg" : imagebase
        }, function(data) {
            data = eval("(" + data + ")");
            $("#head_up").trigger('close');
            headImgPhotoCanvas.setAttribute("height", 235);
            headImgPhotoCanvas.setAttribute("width", 235);
            $("#userHeadImage").attr("src", data.info.substring(1));
        });
    });
    /*
     * get mouse position object {x,y}.
     */
    function getMousePos(canvas, evt) {
        var rect = canvas.getBoundingClientRect();
        return {
            x : evt.clientX - rect.left * (canvas.width / rect.width),
            y : evt.clientY - rect.top * (canvas.height / rect.height)
        };
    }
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值