开发者

Is it possible to clip/mask a div using html5 and canvas?

I have a photo gallery that uses images "cut off" at an odd angle but the cut-out needs to be transparent in order to see the background. I had been able to get it to work using alpha masks but there must be a better way.

Rather than mask each image within the gallery, I wondered whether it might be possible instead to clip/mask the containing div using html5.

I've been able to find a jsfiddle, which I've changed slightly, but it clips an image - not a div. Now I'm having a complete brain freeze and can't think how to change it to clip/mask a div instead.

Some assistance would be much appreciated!

jsfiddle here using code below. Please advise if more info is required.

css:

body {background:#999}
#mycanvas {width:840px;height:457px;border:1px solid red;}

html:

<canvas id="mycanvas"></canvas>

js:

// Grab the Canvas and Draw开发者_如何学运维ing Context
var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');

// Create an image element
var img = document.createElement('IMG');

// When the image is loaded, draw it
img.onload = function () {

    // Save the state, so we can undo the clipping
    ctx.save();


    // Create a shape, of some sort
    ctx.beginPath();
    ctx.moveTo(0, 0);
    ctx.lineTo(840, 0);
    ctx.lineTo(840, 457);
    ctx.lineTo(162, 457);
    ctx.closePath();
    // Clip to the current path
    ctx.clip();


    ctx.drawImage(img, 0, 0);

    // Undo the clipping
    ctx.restore();
}

// Specify the src to load the image
img.src = "http://www.donina.com/donina/clipper.jpg";


You can clip the div's by rotating using css3 other divs. At most you need four divs if you need random angles.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜