小打小闹  

官网demo:http://code.ciaoca.com/jquery/jcrop/demo/crop (只有效果没有代码的demo)

文档:http://code.ciaoca.com/jquery/jcrop/ 

由于似懂非懂最终自己抄了个demo,并结合查询到 canvas 标签,绘制一张新图片达到页面截图图片的效果。

对应的css和js 从文档中的git下载即可。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href="dist/jcrop.css">
    <script type="application/javascript" src="dist/jcrop.js"></script>
</head>
<body>
<div>
    <img id="target" src="https://d3o1694hluedf9.cloudfront.net/market-750.jpg">
</div>
<input type="button" value="确认截图" onclick="cut()">
<div>
    <div id="clipImgDiv"></div>
</div>
</body>
<script type="application/javascript">
    var jcp;
    Jcrop.load('target').then(img => {
        jcp = Jcrop.attach(img, {multi: false,allowResize:false, aspectRatio:2});
        const rect = Jcrop.Rect.sizeOf(jcp.el);
        console.log(rect)
        jcp.newWidget(rect.scale(.7, .5).center(rect.w, rect.h));
        jcp.focus();
    });
    function $(d){
        if(d.startsWith("#")) return document.getElementById(d.replace('#',''))
        else if (d.startsWith(".")) return document.getElementsByClassName(d.replace('.',''))
        else  return document.getElementsByName(d)
    }

    function cut() {
        console.log(jcp.active.pos);
        cropImage($('#target'), jcp.active.pos);
    }

    function cropImage(img,pos) {
        var newCanvas = document.createElement('canvas');
        newCanvas.setAttribute('id', 'newCanvas');
        newCanvas.width = pos.w ;
        newCanvas.height = pos.h ;
        newCanvas.style.border = "1px solid #d3d3d3";
        var newCtx = newCanvas.getContext('2d');
        clipImgDiv.appendChild(newCanvas);
        newCtx.drawImage(img, pos.x, pos.y, pos.w, pos.h, 0, 0, pos.w , pos.h );

        // canvas转化为图片
        var newImage = new Image();
        newImage.crossOrigin = '';
        newImage.src = newCanvas.toDataURL();
        newImage.style.marginLeft = '5px';
        $("#clipImgDiv").appendChild(newImage);


    }
</script>
</html>

最终效果:

 

posted on 2020-09-09 15:33  小打小闹  阅读(258)  评论(0)    收藏  举报