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

会有一股神秘感。 提交于 2019-12-13 13:56:12

问题


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 Drawing 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";

回答1:


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



来源:https://stackoverflow.com/questions/6951342/is-it-possible-to-clip-mask-a-div-using-html5-and-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!