2016-06-21 148 views
0

我有一個問題,我有一個圖像,我想要一些jQuery事件像素化後。 我不想使用pixelate.js或其他插件,它們不適合我的項目。固定寬度的圖像填充div

我想要的是,自動將圖像更改爲使用css圖像渲染的相同圖像的較小「副本」:像素化但沒有圖像的第二副本。這是可能的CSS/JavaScript?

對不起,我的英語不好,謝謝!

+0

你希望它看起來好像圖像改爲較低分辨率的副本,然後擴大規模,以適應大小相同?即圖像會丟失細節,但保持相同的大小? –

+0

是的,那是我想要的。有可能的? – shitwithcode

回答

0

你可以用HTML5的canvas元素來做到這一點。本質上,我們想要將圖像繪製到小畫布上,然後拉伸畫布以填充原始圖像的大小。這裏有一個例子:

$('.image-container').each(function() { 
 
    var canvas = $(this).children('canvas').get(0), 
 
     ctx = canvas.getContext('2d'), 
 
     image = $(this).children('img').get(0), 
 
     imageWidth = $(image).width(), 
 
     imageHeight = $(image).height(), 
 
     scaleFactor = 0.05; 
 
    
 
    canvas.width = scaleFactor * imageWidth; 
 
    canvas.height = scaleFactor * imageHeight; 
 
    ctx.drawImage(image, 0, 0, canvas.width, canvas.height); 
 

 
    $(canvas).width(imageWidth); 
 
    $(canvas).height(imageWidth); 
 
}); 
 

 
$('#toggle-pixelization').on('click', function() { 
 
    $('.image-container').children().toggleClass('hidden') 
 
});
.hidden { 
 
    display: none; 
 
} 
 

 
.image-container canvas { 
 
    image-rendering: -moz-crisp-edges; 
 
    image-rendering: -o-crisp-edges; 
 
    image-rendering: -webkit-optimize-contrast; 
 
    image-rendering: crisp-edges; 
 
    -ms-interpolation-mode: nearest-neighbor; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div class="image-container"> 
 
    <img src="https://placekitten.com/150/150" /> 
 
    <canvas class="hidden"></canvas> 
 
</div> 
 
<button id="toggle-pixelization">Toggle Pixelization</button>

+0

謝謝!有用! – shitwithcode

0
img { 
    height: 100%; 
    width: 100%; 
} 

您可以設置img的大小o是其父項的最大大小。因此,如果父母調整大小,圖像也應相應調整大小。

+0

這將如何幫助我獲得當前圖像像素化? – shitwithcode

+0

那麼,當圖像較小時,您希望它像素化?當更大時,你想清楚嗎? – wmash

+0

目前我有圖像有寬度:100%;它在父母身上。在我的項目中有一些jquery事件後,我不需要改變圖像寬度,只需要像素化圖像。 – shitwithcode

相關問題