var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var img = new Image();
img.onload = function () {
// clips the canvas with provided path function
// if pathFunction is an array, clips with all functions
function clip(pathFunction) {
ctx.beginPath();
if (Array.isArray(pathFunction)) pathFunction.forEach(execute);
else pathFunction();
ctx.clip();
}
// clips the canvas with the invert of provided path function
// if pathFunction is an array, remove clips defined by all functions
function clipRevert(pathFunction) {
ctx.beginPath();
ctx.rect(0, 0, canvas.width, ctx.canvas.height);
if (Array.isArray(pathFunction)) pathFunction.forEach(execute);
else pathFunction();
ctx.clip();
}
function execute(fn) {
return fn();
}
function circlePath(x, y, r) {
ctx.moveTo(x, y, x + r);
ctx.arc(x, y, r, 0, Math.PI * 2, true);
ctx.closePath();
}
function trianglePath() {
ctx.moveTo(80, 100);
ctx.lineTo(50, 150)
ctx.lineTo(110, 150);
ctx.lineTo(80, 100);
}
function clipExample(reverted) {
var clipFunctions = Array.prototype.slice.call(arguments, 1);
ctx.save();
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
if (reverted) clipRevert(clipFunctions);
else clip(clipFunctions);
ctx.drawImage(img, 0, 0);
ctx.restore();
}
window.clipCircleExample = function () {
clipExample(false, circlePath.bind(null, 220, 180, 100));
}
window.clipRevertCircleExample = function () {
clipExample(true, circlePath.bind(null, 220, 180, 100));
}
window.clipRevertTriangleExample = function () {
clipExample(true, trianglePath);
}
window.clipTriangleExample = function () {
clipExample(false, trianglePath);
}
window.clipRevertBothExample =...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.