HTML5のキャンバスを使って画像の透過を行います。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" />
<title>画像の透過</title>
<script type="text/javascript">
// キャンバス
var canvas;
// イメージ
var img = null;
// 透過率
var alpha = 0.1;
/*
画像の描画
*/
function DrawImage() {
// コンテキストの取得
var ctx = canvas.getContext( '2d' );
// 透過度の設定(透過無し)
ctx.globalAlpha = 1;
// キャンバスのクリア
ctx.fillStyle = '#FFFFFF';
ctx.fillRect( 0, 0, canvas.width, canvas.height );
// 透過度の設定(0~1の範囲で指定する)
ctx.globalAlpha = alpha;
// 画像の描画
var posX = ( canvas.width - img.width ) / 2;
var posY = ( canvas.height - img.height ) / 2;
ctx.drawImage( img, posX, posY );
}
/*
ページロード完了
*/
function OnLoad() {
// キャンバス取得
canvas = document.getElementById("canvas");
// イメージ
img = new Image();
img.onload = function () {
// 画像の描画
DrawImage();
// マウスイベントを受け取る
canvas.addEventListener(
"mousedown"
, function (e) {
// 透過率の変更
alpha += 0.1;
if (1.0 < alpha) {
alpha = 0.1;
}
// 画像の描画
DrawImage();
});
};
img.src = "./img/hidekiti.png";
}
</script>
</head>
<body bgcolor="#c0c0ff" onload="OnLoad()">
<h1>画像の透過</h1>
<canvas width="300" height="240" id="canvas" style="background-color:black;"></canvas>
<br />
クリックすると画像の透過度が変わります。
<br />
<a href="../html5_list.html">戻る</a>
</body>
</html>