ページの背景をQRコードにする
オンラインMTGで画面共有中のURLについて、参加者が「そのページのURLはどこ?」と迷子になることがある
そこで、ページの背景にURLのQRコードを埋め込んでおく
すると、迷子になった参加者は、共有された画面をスマホのカメラで読み取ることで、ページのURLを手に入れられる
https://gyazo.com/778dd9fc39195ea2cd93bd61b129db68
インストール
マイページに以下をペースト
code:install
code:script.js
import '/api/code/hitode909/ページの背景をQRコードにする/script.js';
code:script.js
(function() {
// QRCodeライブラリを動的にロード
function loadQRCodeLibrary() {
return new Promise((resolve, reject) => {
if (window.QRCode) {
resolve();
return;
}
const script = document.createElement('script');
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
});
}
function generateQRCodeBackground() {
const currentUrl = location.href;
// 一時的なdiv要素を作成
const tempDiv = document.createElement('div');
tempDiv.style.position = 'absolute';
tempDiv.style.left = '-9999px';
document.body.appendChild(tempDiv);
// QRコードを生成
const qrcode = new QRCode(tempDiv, {
text: currentUrl,
width: 160,
height: 160,
colorDark: '#666666',
colorLight: '#F0F0F0'
});
// QRコード生成完了を待つ
setTimeout(() => {
const originalCanvas = tempDiv.querySelector('canvas');
if (originalCanvas) {
// マージン付きの新しいCanvasを作成
const marginCanvas = document.createElement('canvas');
marginCanvas.width = 200;
marginCanvas.height = 200;
const ctx = marginCanvas.getContext('2d');
// 背景を薄い灰色で塗りつぶし
ctx.fillStyle = '#F0F0F0';
ctx.fillRect(0, 0, 200, 200);
// QRコードを中央に配置(20pxのマージン)
ctx.drawImage(originalCanvas, 20, 20);
// マージン付きCanvasをData URLに変換して背景に設定
const qrCodeDataUrl = marginCanvas.toDataURL();
document.body.style.backgroundImage = url(${qrCodeDataUrl});
document.body.style.backgroundRepeat = 'repeat'; // 縦横ともにrepeat
}
// 一時的な要素を削除
document.body.removeChild(tempDiv);
}, 100);
}
function setupSPAMonitoring() {
let currentUrl = location.href;
// History APIをオーバーライドしてSPA遷移を検知
const originalPushState = history.pushState;
const originalReplaceState = history.replaceState;
history.pushState = function() {
originalPushState.apply(history, arguments);
setTimeout(() => {
if (location.href !== currentUrl) {
currentUrl = location.href;
generateQRCodeBackground();
}
}, 0);
};
history.replaceState = function() {
originalReplaceState.apply(history, arguments);
setTimeout(() => {
if (location.href !== currentUrl) {
currentUrl = location.href;
generateQRCodeBackground();
}
}, 0);
};
// popstateイベント(戻る/進むボタン)を監視
window.addEventListener('popstate', () => {
setTimeout(() => {
if (location.href !== currentUrl) {
currentUrl = location.href;
generateQRCodeBackground();
}
}, 0);
});
// ハッシュ変更も監視
window.addEventListener('hashchange', () => {
if (location.href !== currentUrl) {
currentUrl = location.href;
generateQRCodeBackground();
}
});
}
function init() {
loadQRCodeLibrary()
.then(() => {
generateQRCodeBackground();
setupSPAMonitoring();
})
.catch((error) => {
console.error('Failed to load QRCode library:', error);
});
}
// DOM読み込み完了後に実行
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
})();