首页 > 解决方案 > 使用 css 显示图像的一部分,但使用 img-responsive 进行响应

问题描述

我创建了一个系统,用户将在其中上传图像,将其调整为特定宽度,然后用户可以裁剪图像(使用 imgAreaSelect 但升级到 Jcrop 以添加移动使用)。

我有这一切工作正常。一旦用户将 Jcrop 的选择器移动到他们想要的位置并选择保存按钮,我让 jQuery 编写一些精美的 CSS 来显示用户想要的图像部分(其余部分通过隐藏overflow: hidden)加上更多表单以添加照片信用和其他有关照片的信息。

这又一次,很好用......在桌面上。移动设备上的图像是全尺寸的,并且没有响应,因此您看不到照片的大部分内容。我一直在努力解决这个问题(除了禁用预览照片)。有没有办法让我的方法响应?

$(document).on('click','#save-image',function() {
    //$('img.mobimg').imgAreaSelect({remove:true});
    //$('#the-image').fadeOut();
    //Write the preview image using variables from image selector.
    $('#the-image').fadeOut().html('<div align="center"><div id="img" style="position: relative; width: '+$('#w').val()+'px; height: '+$('#h').val()+'px; overflow: hidden;">'+
                            '<img src="'+theimg+'" id="finished-image" style="position: absolute; top: -'+$('#y1').val()+'px; left: '+$('#x1').val()+'px;">'+
                          '</div></div><hr>').fadeIn(function() { $('#finished-image').addClass('img-responsive'); });
    // Fade in form to allow user to finish adding details.
    $('.form-finish').fadeIn();
    // Fade in main form submit button to allow user to submit the completed form.
    $('.panel-footer').fadeIn();  // Final Submit Button to Fade In
    
    jcrop_api.destroy();
});

标签: javascripthtmljquerycssjcrop

解决方案


使用 CSS 修剪图像对于比图像本身更宽的桌面效果很好,但是在响应式调整图像大小时几乎不可能,因为图像的宽度和高度总是随着设备的变化而变化。

反而; 我转向 JavaScript,它实际上将图像修剪为所需的宽度和高度以及所需的位置,由 Jcrop 设置,然后img-responsive将图像调整到移动设备的大小没有问题。

function showPart(img, offsetTop, offsetLeft, width, height){
    var src = img.src;
    $(img).replaceWith("<canvas id='cnvs' class='img-responsive' style='max-width:100%;'></canvas>");
    var canvas = document.getElementById('cnvs');
    canvas.height = height;
    canvas.width = width;
    var ctx = canvas.getContext("2d");
    var img = new Image();
    img.onload = function(){
        ctx.drawImage(this, offsetLeft, offsetTop, width, height, 0, 0, width, height);
    };
    img.src = src;
}

包含此片段的原始答案:https ://stackoverflow.com/a/36436245/956106


推荐阅读