スクラッチ風に擦ると文字が浮かび上がってくるデザイン

トップコンテンツ

スクラッチ風に擦ると文字が浮かび上がってくるデザイン

コメント

スクラッチ風にマウスをホバーすると背景が削れ文字が浮かび上がってくる処理です。

マウスを動かすと、背景が削れます。
スマホやタブレットでは、画面をタッチして指でなぞると、背景が削れます。

文字が見える!

document.addEventListener('DOMContentLoaded', () => { 
	// 初期設定
    const canvas = document.getElementById("mask");
    const ctx = canvas.getContext("2d");
    const container = document.getElementById("container");

    // キャンバスのサイズをコンテナに合わせる
    canvas.width = container.offsetWidth;
    canvas.height = container.offsetHeight;

    // キャンバスを黒で塗りつぶし
    ctx.fillStyle = "#959595";
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // マウスで水をかけるような効果
    canvas.addEventListener("mousemove", (e) => {
      const rect = canvas.getBoundingClientRect();
      const x = e.clientX - rect.left;
      const y = e.clientY - rect.top;

      ctx.globalCompositeOperation = "destination-out";
      ctx.beginPath();
      ctx.arc(x, y, 30, 0, Math.PI * 2, false); // 円形に透明化
      ctx.fill();
    });

    // タッチ対応(スマホなど)
    canvas.addEventListener("touchmove", (e) => {
      e.preventDefault();
      const rect = canvas.getBoundingClientRect();
      const touch = e.touches[0];
      const x = touch.clientX - rect.left;
      const y = touch.clientY - rect.top;

      ctx.globalCompositeOperation = "destination-out";
      ctx.beginPath();
      ctx.arc(x, y, 30, 0, Math.PI * 2, false); // 円形に透明化
      ctx.fill();
    });
});
<div id="container">
  <div style="z-index: 1; position: relative;">文字が見える!</div>
  <canvas id="mask"></canvas>
</div>
#container {
	position: relative;
	width: 50%;
	height: 200px;
	font-size: 4.0rem;
	font-weight: 900;
	text-align: center;
	color: #000000;
	background: #FFFFFF;
	overflow: hidden;
	user-select: none;
	
	display: flex;
	justify-content: center;
	align-items: center;
    margin: 0 auto;
}

#mask {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	z-index: 2;
}
コメント

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

ボトムコンテンツ