けしごむ
道具の最後は けしごむです。
けしごむは、実は新しい仕組みをほとんど使いません。 「白くて太いペン」として作れてしまいます。
今回さわる
app/:index.htmlにボタン 1 つ、main.jsの 2 行を書き換え
前の節を終えていない人は、ここから始められます。
けしごむは「白い太いペン」
Section titled “けしごむは「白い太いペン」”キャンバスの背景は白(#ffffff)です。
そこに白い線を引けば、下に描いてあったものが隠れて、消えたように見えます。
図: 実際には「消して」いない。白で上塗りしている。
この作り方には、うれしい副作用があります。
送る指示の種類が増えません。line のまま、色と太さを変えるだけです。
受け取り側は「白くて太い線が来た」としか思いませんが、結果は同じになります。
ボタンを足す
Section titled “ボタンを足す”index.html の .tools の中(ペンの下)
2020<button class="tool selected" data-tool="pen">🖊 ペン</button>21<button class="tool" data-tool="eraser">🧽 けしごむ</button>書き足すのはこれだけです。JavaScript 側にボタンの処理は要りません。
けしごむのボタンには class="tool" を付けたので、
04 節 で書いた .tool のループがそのまま拾ってくれます。
// 04 節で書いたこれが、けしごむのボタンも面倒を見てくれるdocument.querySelectorAll('.tool').forEach(function (button) { button.addEventListener('click', function () { tool = button.dataset.tool; select(button, '.tool, .stamp'); });});data-tool="eraser" と書いておけば、押されたときに tool が 'eraser' になります。
道具を増やすたびに JavaScript を書き足さなくていい形になっているわけです。
けしごむで描く
Section titled “けしごむで描く”あとは、線を引くときの色と太さを道具によって切り替えるだけです。
main.js を変更する
Section titled “main.js を変更する”main.js の pointermove の中
155155 y1: last.y,156156 x2: pos.x,157157 y2: pos.y,158 color: color,159 width: 4,158 // けしごむは「背景と同じ白い色で、太く描くペン」として作る159 color: tool === 'eraser' ? '#ffffff' : color,160 width: tool === 'eraser' ? 40 : 4,160161});161162
162163last = pos;条件 ? A : B は三項演算子です。「条件が成り立てば A、そうでなければ B」を 1 行で書けます。
// 上の書き方は、これと同じ意味let lineColor;if (tool === 'eraser') { lineColor = '#ffffff';} else { lineColor = color;}けしごむのときだけ太さを 40 にしているのは、
細いけしごむだと消すのが大変だからです。
送っているものは、やっぱり線
Section titled “送っているものは、やっぱり線”けしごむでなぞったときに飛んでいく指示を見てみます。
{ type: 'line', x1: ..., y1: ..., x2: ..., y2: ..., color: '#ffffff', width: 40 }type は line のままです。受け取った側は「白くて太い線を引け」としか読みません。
それでも画面は同じになります。
05 節 で書いた「見た目に必要な情報は、すべて指示に入れる」を 守っているので、新しい種類の指示を作らなくても済んでいるわけです。
けしごむを選んでなぞると、線が消えます。相手の画面でも消えます。
けしごむで消したあと、もう一度ペンに戻して描けることも確かめてください。
tool を切り替えているだけなので、行ったり来たりできます。
次の節で、「ぜんぶ消す」ボタンを足します。
この節を終えたときのディレクトリ
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> </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 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); }}
// 自分のキャンバスに描いてから、同じ指示を相手にも送る。// 「描く」と「送る」を必ずセットにするので、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'); });});
// 同じ仲間のボタンから選択の印を外して、押されたものだけに付ける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;}