Skip to content

Instantly share code, notes, and snippets.

@LeaVerou
Created January 17, 2013 19:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save LeaVerou/4558732 to your computer and use it in GitHub Desktop.
Save LeaVerou/4558732 to your computer and use it in GitHub Desktop.
Clip image to hexagon
/**
* Clip image to hexagon
*/
img {
max-width: 200px;
max-height: 200px;
}
<h1>Clip image to hexagon</h1>
<p>Edit the HTML source and run the JS.
Right click the hexagon and Save Image As… (Firefox lets you do that)</p>
<img src="http://w3.org/conf/img/speakers/lea.jpg" />
<img src="http://w3.org/conf/img/speakers/lea.jpg" class="hexagon" />
function $$(expr, con) {
var elements = (con || document).querySelectorAll(expr);
return Array.prototype.slice.call(elements);
}
// Clip the speaker images to hexagons
(function() {
var hexagon = new Image();
hexagon.src = 'http://w3.org/conf/img/hexagon.svg';
hexagon.onload = function() {
hexagon.aspectRatio = hexagon.width / hexagon.height;
$$('img.hexagon').forEach(function(img) {
img.onload = function() {
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
canvas.width = this.offsetHeight * hexagon.aspectRatio;
canvas.height = this.offsetHeight;
['className', 'title', 'alt'].forEach(function(property) {
if (this[property]) {
canvas[property] = this[property];
}
}, this);
var args = [this];
var aspectRatio = this.naturalWidth / this.naturalHeight;
if (aspectRatio >= hexagon.aspectRatio) {
// Clip a rectangle from the center with the maximum height and
// the same aspect ratio as the hexagon
var clipWidth = this.naturalHeight * hexagon.aspectRatio;
args.push((this.naturalWidth - clipWidth)/2, 0, clipWidth, this.naturalHeight);
}
else {
var clipHeight = this.naturalWidth / hexagon.aspectRatio;
args.push(0, (this.naturalHeight - clipHeight)/2, this.naturalWidth, clipHeight);
}
args.push(0, 0, canvas.width, canvas.height);
ctx.drawImage.apply(ctx, args);
ctx.globalCompositeOperation = 'destination-atop';
var width = canvas.width * hexagon.aspectRatio;
ctx.drawImage(hexagon, 0, 0, canvas.width, canvas.height);
this.parentNode.replaceChild(canvas, this);
}
if(img.complete) {
img.onload();
}
});
};
})();
{"view":"split-vertical","fontsize":"100","seethrough":"","prefixfree":"1","page":"html"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment