Search code examples
cssimagecss-shapes

how can I get a trapeze image without distorting the image?


I'm trying to present the image in a trapeze form without messing with the actual image nor using skew. How can I do it?


Solution

  • You can use a canvas for this resulting in this:

    From demo

    Online demo here

    A simple adjustment of the HTML to use a canvas instead:

    <div class="box">
        <canvas id="canvas"></canvas>
    </div>    
    

    Remove some of the CSS rule specifications:

    .box{
        height:300px;  
        overflow:hidden;
    }
    
    .box > canvas {
        height: 100%;
        width: 100%;
    }
    

    And add this in the JavaScript section:

    var img = new Image,
        ctx = document.getElementById('canvas').getContext('2d');
    
    /// load image dynamically (or use an existing image in DOM)
    img.onload = draw;
    img.src = 'http://cssglobe.com/lab/angled/img.jpg';
    
    function draw() {
    
        /// set canvas size = image size
        var w, h;
        canvas.width = w = this.naturalWidth;
        canvas.height = h = this.naturalHeight;
    
        /// draw the trapez shape
        ctx.moveTo(0, h * 0.25);
        ctx.lineTo(w, 0);
        ctx.lineTo(w, h);
        ctx.lineTo(0, h * 0.75);
    
        /// make it solid
        ctx.fill();
    
        /// change composite mode to replace the solid shape
        ctx.globalCompositeOperation = 'source-in';
    
        /// draw in image
        ctx.drawImage(this, 0, 0);
    }
    

    This works in all modern browsers. If that's not needed then palpatim's approach is quicker.

    Hope this helps.