画像自体を加工しないでHTML上で写真をハート型や星型に切り取る方法

スポンサーリンク
背景を透過にして写真を切り取るには、PhotoshopやFireworksで加工する方法が一般的ではありますが、あえて写真には手を加えず、HTML上で切り取りたいときもありませんか?
え、ないって?・・・・。
あると思うよ多分・・・。
でも、けっこう面白い技術だと思うので、紹介します。
jpeg画像を切り取って背景透過できるから、透過pngを使用するよりもファイルサイズの軽減にもなります。
元ネタはこちらのページ
http://hedgerwow.blogspot.jp/2010/10/re-jpegs-with-alpha-channels.html
素晴らしいことにIEにも対応してくれちゃってます。
仕組みは、写真画像と、背景透過のpng画像2つを用意し、合成します。pngの透過部分が見事にjpeg写真画像を透過にして、あたかも写真を切り取ったように見えます。

javascript
<script>
function createAlphaImage(img) {
var alphaSrc = img.getAttribute('data-alpha-src')
if(!alphaSrc) {
return;
}
// Then preload alpha mask
var alpha = document.createElement('img');
alpha.onload = function() {
onAlphaImageLoad_(img, alpha);
alpha.onload = null;
alpha = null;
img = null;
};
alpha.src = alphaSrc;
}
function onAlphaImageLoad_(img, alpha) {
useCanvas_(img, alpha) ||
useMsFilter_(img, alpha);
}
function useCanvas_(img, alpha) {
var canvas = document.createElement('canvas');
if (!canvas.getContext) {
canvas = null;
return false;
}
canvas.width = img.width;
canvas.height = img.height;
img.parentNode.replaceChild(canvas, img);
// Canvas compositing code
// See https://developer.mozilla.org/en/Canvas_tutorial/Compositing
var context = canvas.getContext('2d');
context.clearRect(0, 0, img.width, img.height);
context.drawImage(img, 0, 0, img.width, img.height);
// Create the mask
context.globalCompositeOperation = 'xor';
context.drawImage(alpha, 0, 0, img.width, img.height);
context.globalCompositeOperation = 'xor';
// Use that mask to redraw the same image.
context.drawImage(img, 0, 0, img.width, img.height);
return true;
}
function useMsFilter_(img, alpha) {
if (!img.filters) {
return false;
}
var canvas = document.createElement('canvas');
var display = img.currentStyle.display;
canvas.style.display = display == 'inline' || display == 'inline-block'
? 'inline-block' :
display;
canvas.style.width = img.width + 'px';
canvas.style.height = img.height + 'px';
var mask = document.createElement('span');
mask.style.cssText = [
'position:relative;',
'display:inline-block;',
'width:100%;',
'height:100%;'
].join('');
mask.style.filter = 'progid:DXImageTransform.Microsoft.Compositor(function=17, duration=0)';
img.style.zIndex = 2;
alpha.style.zIndex = 1;
img.parentNode.insertBefore(canvas, img);
canvas.appendChild(mask);
mask.appendChild(alpha);
mask.filters.item(0).Apply();
mask.appendChild(img);
mask.filters.item(0).Play();
return true;
}
window.onload = function() {
createAlphaImage(document.getElementById('demo'));
};
</script>
HTML
<!doctype html> <html lang="ja"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=7" /> </head> <body> <img id="demo" src="img/girl.jpg" data-alpha-src="img/alpha.png" /> </body> </html>
WordPressのプラグインとしてハート型や星型のプロフィール写真とか、ギャラリーとかのモジュールを作ってみたら重要あるかな?
スポンサーリンク