ぜんぶ消す
けしごむは、なぞったところだけを消す道具でした。 この節では、キャンバスをまるごと白紙に戻すボタンを足します。
けしごむが line を送っていたのに対して、こちらは新しい種類の指示を作ります。
とはいえ、いままででいちばん短い指示になります。
今回さわる
app/:index.htmlにボタン 1 つ、main.jsに 3 か所
前の節を終えていない人は、ここから始められます。
ボタンを足す
Section titled “ボタンを足す”けしごむと違って、こちらは道具ではありません。
「選んで使うもの」ではなく「押したら即座に効くもの」なので、class="tool" は付けません。
index.html の .tools の最後(スタンプの下)
32 <button id="clear">ぜんぶ消す</button>3133</div>class ではなく id を付けたのは、押されたときの処理を自分で書くからです。
ボタンを取り出す
Section titled “ボタンを取り出す”main.js の先頭
55const statusText = document.querySelector('#status');6const clearButton = document.querySelector('#clear');67const canvas = document.querySelector('#canvas');clear という指示を作る
Section titled “clear という指示を作る”apply に、新しい種類の指示を受け付ける枝を足します。
main.js の apply
8081function apply(data) {8182 if (data.type === 'line') {8283 drawLine(data.x1, data.y1, data.x2, data.y2, data.color, data.width);8384 }8485 if (data.type === 'stamp') {8586 drawStamp(data.x, data.y, data.emoji);8687 }88 if (data.type === 'clear') {89 clearCanvas();90 }8791}clearCanvas は 01 節 で書いたきり、
最後に 1 回呼んで白くするだけの関数でした。ここでようやく出番が来ます。
ボタンを押せるようにする
Section titled “ボタンを押せるようにする”main.js(.color のループの下、select の上)
203clearButton.addEventListener('click', function () {204 draw({ type: 'clear' });205});draw({ type: 'clear' }) を呼ぶだけで、自分のキャンバスが白くなり、
同じ指示が相手にも飛んで相手の画面も白くなります。
03 節 で apply と draw を分けた土台が、ここでもそのまま効いています。
「描いて、送る」を自分で書く必要はありません。
指示に入れるのは、必要な情報だけ
Section titled “指示に入れるのは、必要な情報だけ”送っている指示は { type: 'clear' } だけです。座標も色も太さもありません。
図: 「ぜんぶ消して」を伝えるのに、それ以上の情報は要らない。
05 節 では「見た目に必要な情報は、すべて指示に入れる」と書きました。 これは裏を返すと「要らない情報は入れない」でもあります。
line… どこに・何色で・どの太さで引くかが分からないと、相手の画面が違う絵になるclear… 「全部消して」で足りる。それ以上は相手も知る必要がない
指示は小さいほど速く届きます。1 秒に何十回も飛ぶ line を軽くしておくのは効きますし、
clear のように減らせるものはとことん減らしてかまいません。
「ぜんぶ消す」を押すと、両方の画面が白紙になります。
つないでいないときに押しても、自分の画面だけが白くなります。
draw の中の if (conn) が、送る相手がいないことを見てくれているからです。
これでお絵かきツールとしては完成です。次の節で最後の仕上げをして、公開します。
この節を終えたときのディレクトリ
Section titled “この節を終えたときのディレクトリ”<!doctype html><html lang="ja"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>ぜんぶ消す</title> <link rel="stylesheet" href="style.css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/peerjs/1.5.5/peerjs.min.js"></script> <script src="main.js" defer></script> </head> <body> <header> <input id="peer-id" placeholder="あいことば" /> <button id="host">へやをつくる</button> <button id="guest">へやにはいる</button> <span id="status">まだつながっていません</span> </header>
<div class="tools"> <button class="tool selected" data-tool="pen">🖊 ペン</button> <button class="tool" data-tool="eraser">🧽 けしごむ</button>
<button class="color selected" data-color="#333333"></button> <button class="color" data-color="#e5484d"></button> <button class="color" data-color="#f5a524"></button> <button class="color" data-color="#17c964"></button> <button class="color" data-color="#006fee"></button> <button class="stamp" data-stamp="🐱">🐱</button> <button class="stamp" data-stamp="🌸">🌸</button> <button class="stamp" data-stamp="⭐">⭐</button>
<button id="clear">ぜんぶ消す</button> </div>
<div class="stage"> <canvas id="canvas" width="800" height="600"></canvas> </div> </body></html>// 画面の部品を取っておくconst peerIdInput = document.querySelector('#peer-id');const hostButton = document.querySelector('#host');const guestButton = document.querySelector('#guest');const statusText = document.querySelector('#status');const clearButton = document.querySelector('#clear');const canvas = document.querySelector('#canvas');const ctx = canvas.getContext('2d');
// つながった相手との通り道。まだつながっていないので null。let conn = null;
// いま選んでいる道具と色とスタンプlet tool = 'pen';let color = '#333333';let stamp = '🐱';
// 画面の「あいことば」= ピア ID。ここから PeerJS Cloud で名乗る名前を作る。// PeerJS Cloud は世界中の人と共有しているので「test」のような短い名前は// すでに誰かに使われている。長めの前置きを付けてぶつかりにくくする。function roomId(peerId) { return 'webrtc-handson-' + peerId;}
// へやをつくる側(ホスト)。ピア ID を自分の名前として名乗り、誰かが来るのを待つ。hostButton.addEventListener('click', function () { const peer = new Peer(roomId(peerIdInput.value));
peer.on('open', function () { statusText.textContent = 'あいてを待っています…'; });
peer.on('connection', function (newConn) { conn = newConn; conn.on('open', ready); });
peer.on('error', showError);});
// へやにはいる側(ゲスト)。名前は名乗らず、ピア ID の相手に向かってつなぎに行く。guestButton.addEventListener('click', function () { const peer = new Peer();
peer.on('open', function () { conn = peer.connect(roomId(peerIdInput.value), { reliable: true }); conn.on('open', ready); });
peer.on('error', showError);});
// PeerJS から届くエラーを、日本語のことばにして出す。// err.type にどんなエラーかが入っている。function showError(err) { if (err.type === 'unavailable-id') { statusText.textContent = 'そのあいことばは使われています。別のあいことばにするか「へやにはいる」を押してください'; } else if (err.type === 'peer-unavailable') { statusText.textContent = 'そのあいことばのへやが見つかりません。相手が「へやをつくる」を押したか確かめてください'; } else { statusText.textContent = 'つながりませんでした(' + err.type + ')'; }}
// ホストでもゲストでも、つながったあとにやることは同じ。function ready() { statusText.textContent = 'つながりました';
conn.on('close', function () { statusText.textContent = 'せつだんされました'; });
// 相手から届いた指示も、自分が出した指示と同じ apply に通す。 conn.on('data', apply);}
// 指示のとおりにキャンバスへ描く。// 自分が出した指示も、相手から届いた指示も、かならずここを通る。function apply(data) { if (data.type === 'line') { drawLine(data.x1, data.y1, data.x2, data.y2, data.color, data.width); } if (data.type === 'stamp') { drawStamp(data.x, data.y, data.emoji); } if (data.type === 'clear') { clearCanvas(); }}
// 自分のキャンバスに描いてから、同じ指示を相手にも送る。// 「描く」と「送る」を必ずセットにするので、2 つの画面が同じ絵になる。function draw(data) { apply(data);
if (conn) { conn.send(data); }}
function drawLine(x1, y1, x2, y2, lineColor, lineWidth) { ctx.strokeStyle = lineColor; ctx.lineWidth = lineWidth; ctx.lineCap = 'round'; ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.stroke();}
function drawStamp(x, y, emoji) { ctx.font = '48px sans-serif'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText(emoji, x, y);}
function clearCanvas() { ctx.fillStyle = '#ffffff'; ctx.fillRect(0, 0, canvas.width, canvas.height);}
// canvas は 800x600 のまま、空いている場所に合わせて縮めて表示している。// クリックされた位置は「画面上の px」なので、縮めた比率で割って// 800x600 の中での座標に戻す。これをやらないと 2 台で線がズレる。function positionOf(event) { const rect = canvas.getBoundingClientRect();
return { x: ((event.clientX - rect.left) / rect.width) * canvas.width, y: ((event.clientY - rect.top) / rect.height) * canvas.height, };}
// 直前のペン先の位置。線は「前の点から今の点まで」をつなげて描く。let last = null;
canvas.addEventListener('pointerdown', function (event) { const pos = positionOf(event);
if (tool === 'stamp') { draw({ type: 'stamp', x: pos.x, y: pos.y, emoji: stamp }); return; }
last = pos;});
canvas.addEventListener('pointermove', function (event) { if (last === null) return;
const pos = positionOf(event);
draw({ type: 'line', x1: last.x, y1: last.y, x2: pos.x, y2: pos.y, // けしごむは「背景と同じ白い色で、太く描くペン」として作る color: tool === 'eraser' ? '#ffffff' : color, width: tool === 'eraser' ? 40 : 4, });
last = pos;});
canvas.addEventListener('pointerup', function () { last = null;});
canvas.addEventListener('pointerleave', function () { last = null;});
document.querySelectorAll('.tool').forEach(function (button) { button.addEventListener('click', function () { tool = button.dataset.tool; select(button, '.tool, .stamp'); });});
document.querySelectorAll('.stamp').forEach(function (button) { button.addEventListener('click', function () { tool = 'stamp'; stamp = button.dataset.stamp; select(button, '.tool, .stamp'); });});
document.querySelectorAll('.color').forEach(function (button) { // ボタンの見た目の色を data-color から流し込む button.style.background = button.dataset.color;
button.addEventListener('click', function () { color = button.dataset.color; select(button, '.color'); });});
clearButton.addEventListener('click', function () { draw({ type: 'clear' });});
// 同じ仲間のボタンから選択の印を外して、押されたものだけに付けるfunction select(button, group) { document.querySelectorAll(group).forEach(function (other) { other.classList.remove('selected'); }); button.classList.add('selected');}
clearCanvas();body { box-sizing: border-box; /* 画面(iframe やスマホ)の高さぴったりに収めて、ページごと縦スクロールしないようにする */ height: 100dvh; display: flex; flex-direction: column; margin: 0; padding: 16px; font-family: sans-serif; background: #222; color: #fff;}
header,.tools { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-bottom: 12px;}
input,button { font-size: 16px; padding: 6px 10px;}
.color { width: 32px; height: 32px; padding: 0; border: 2px solid #fff; border-radius: 50%; /* 色そのものは data-color から JavaScript で流し込む */}
/* いま選んでいる道具・色が分かるようにする */.selected { outline: 3px solid #ffd60a;}
/* キャンバスを置く場所。上のバーを引いた残りの高さを、ここが全部使う */.stage { flex: 1; /* flex の中身は既定では縮まないので、縮んでよいことを伝える */ min-height: 0;}
canvas { display: block; background: #fff; border-radius: 8px; /* 実際の解像度は 800x600 のまま、あいている場所に収まる大きさで表示する。 こうすると、どの端末でも同じ座標で絵を共有できて、画面もスクロールしない。 */ max-width: 100%; max-height: 100%; /* 指でなぞったときにページがスクロールしないようにする(スマホ用) */ touch-action: none;}