Search code examples
htmlcssresponsive-designresize-crop

Resizing and cropping an image in HTML5 and css


My requirements -

  1. A random image gets displayed inside div/canvas
  2. Image height should get adjusted to parent height
  3. Image width should get re-sized proportionately (with height)
  4. If image width is more than parent width, crop from left and right equally

I have achieved this with java script. Jsfiddle is at http://jsfiddle.net/yesprasoon/N3WvF/. You can resize the output window to see how it is working.

However I feel that I am doing it tedious way and there is something very simple in CSS and/or jQuery. could you please help me with pure css (preferably)?

I am attaching java script here as well -

var strDataURI;
//
displayBackground(true);
//
window.onresize = function(event) {
 displayBackground(false);
}
//
function displayBackground(bChangeImage)
{
 //alert("displayBackground");
 var appWidth = window.innerWidth;
 var appHeight = window.innerHeight;
 //
 if (bChangeImage)
 {
   var suffix_array = ["_california","_easter","_eiffel","_hk","_taj"];
   var ran = Math.floor((Math.random()*5)+1);
   ran = ran - 1;
   //ran = 3;
   strDataURI = "http://minds-eye.info/TP_Test/TP"+suffix_array[ran]+".jpg";
 }
 //
 var myCanvas = document.getElementById('canvas');
 var ctx = myCanvas.getContext('2d');
 var img = new Image;
 img.onload = function(){
  ctx.canvas.width  = appWidth;
  ctx.canvas.height = appHeight;
  //
  var hFraction = appHeight / img.naturalHeight;
  var displayWidth = img.naturalWidth*hFraction;
  mrgLeft = (appWidth - displayWidth)/2;
  mrgTop = (appHeight - img.naturalHeight)/2;
  ctx.drawImage(img,mrgLeft,0, displayWidth, appHeight);
  //blurMargin = 20;
  //stackBlurCanvasRGB( "canvas", blurMargin, blurMargin, appWidth-blurMargin*2, appHeight-blurMargin*2, 6 );
  };
 img.src = strDataURI;
 }

Solution

  • This should do the trick :

    FIDDLE

    HTML:

    <div id="canvasHolder">
    </div>
    

    CSS

    #canvasHolder{
        background: white url(http://placekitten.com/400/700) no-repeat center center;
        background-size: auto 100% ;
        height:100%;
        width:100%;
    }