canvas压缩图片,canvas,css结合绘制正方形图片

//------------ 对图片进行压缩 
    function compress(imgPath) {
        var image = new Image();
        //新建一个img标签(还没嵌入DOM节点) 
        image.src = imgPath;
        image.onload = function() {
            var canvas = document.createElement('canvas');
            var    context = canvas.getContext('2d');
            var    imageWidth = image.width / 3;
                //压缩后图片的大小 
            var    imageHeight = image.height / 3;
            var data = '';
            canvas.width = imageWidth; 
            canvas.height = imageHeight;
            context.drawImage(image, 0, 0, imageWidth, imageHeight);
            data = canvas.toDataURL('image/jpeg')
            //压缩完成 
            $(".srcDiscernImg").attr("src", data);
            console.log("渲染。。。。");
        }
    }

//————-canvas,css结合绘制正方形图片

html

        <div class="l-search-img">
            <img src="" id="imageSearchSrc">
        </div>
        

css

    .proimg-search-top .l-search-img{ width:140px; height:140px;margin-bottom: 10px;position:relative;background-color:#fff; }
    .proimg-search-top .l-search-img img{ position:absolute;left:50%;top:50%; -moz-transform:translate(-50%,-50%);-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%) }
    

js

 // 对图片进行绘制,在div里显示成正方形
var searchImgPath = '拿到图片地址';
var searchImgSize ="140";//要生成的正方形尺寸
compress(searchImgPath,searchImgSize);

    // 对图片进行绘制,在div里显示成正方形
function compress(imgPath,maxSize) {
    var image = new Image();
    //新建一个img标签(还没嵌入DOM节点)
    image.src = imgPath;
    image.onload = function() {
        var canvas = document.createElement('canvas');
        var context = canvas.getContext('2d');
        var imageWidth = image.width;
        //压缩后图片的大小
        var imageHeight = image.height;        
       if(imageWidth > imageHeight){//横的图片
            var imgSize = imageWidth/imageHeight;
            imageWidth = maxSize;
            imageHeight = imageWidth / imgSize;

        }else if(imageWidth < imageHeight){//竖的图片
            var imgSize = imageWidth/imageHeight;
            imageHeight = maxSize;
            imageWidth = imageHeight * imgSize;
        } else{  //如果为正方形
           imageWidth = image.width;
           imageHeight = image.height;
       }
        var data = '';
        canvas.width = imageWidth;
        canvas.height = imageHeight;
        context.drawImage(image, 0, 0, imageWidth, imageHeight);
        data = canvas.toDataURL('image/jpeg')
        //压缩完成
        $("#imageSearchSrc").attr("src", data);

    }
}
    原文作者:我在神游
    原文地址: https://segmentfault.com/a/1190000018805765
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞