Skip to content Skip to sidebar Skip to footer

Displaying Div Inside A Canvas Clipping Path

I have a DIV container that I want to place inside a Canvas element, how do I set the clipping path of the #canvasContents to the Canvas shape?

Solution 1:

Live Demo

Here is one way to accomplish it, first I put the canvas element over the div just using absolute positioning like so

canvas {
    position:absolute
}
#canvasContents {
    position:absolute;
    background:blue;
    width:500px;
    height:400px;
    line-height:400px;
    text-align:center
}

Then I fill the canvas and use clipping to show the effect.

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var x = 120,
    y = 70;
context.fillRect(0, 0, canvas.width, canvas.height);

context.save();
context.beginPath();
context.moveTo(x, y);
context.bezierCurveTo(x, y, x + 6, y - 82, x + 98, y - 25);
context.bezierCurveTo(x + 210, y - 5, x + 325, y + 2, x + 283, y + 78);
context.bezierCurveTo(x + 244, y + 173, x + 237, y + 270, x + 138, y + 235);
context.bezierCurveTo(x - 29, y + 185, x - 145, y + 154, x - 65, y + 99);
context.closePath();
context.clip();
context.clearRect(0, 0, canvas.width, canvas.height);
ctx.restore();

The key with clipping is to save the context, draw your path, and then call clip. After that you can do a fill, or in this example a clearRect which will show whatever is positioned behind the canvas element.

Post a Comment for "Displaying Div Inside A Canvas Clipping Path"