相手のカーソルを表示する
相手のペン先の位置に、小さい丸を出します。 線が出てくる前に「いま相手がここにいる」が見えるので、相手がいる感じが一気に増えます。
04 章の完成コードに、この機能だけを足したものが ページの下に置いてあります。
今回さわる
app/: 3 ファイルとも少しずつ
前の節を終えていない人は、ここから始められます。
カーソルは「絵」ではない
Section titled “カーソルは「絵」ではない”いままで送ってきた指示は、ぜんぶキャンバスに残るものでした。
だから draw を通し、apply でキャンバスに描き、history に貯めました。
カーソルは違います。
- キャンバスに描いてはいけない(描いたら跡が残る)
historyに貯めてはいけない(あとから送り直しても意味がない)- 届かなくても、次の位置がすぐ来るので困らない
つまり draw を通してはいけない指示です。専用の道を作ります。
図: 同じ通り道(conn)を使うが、通す前の扱いが違う。
丸を置く場所を作る
Section titled “丸を置く場所を作る”キャンバスの上に重ねるので、両方を包む枠を用意します。
index.html を変更する
Section titled “index.html を変更する”index.html の .stage(<canvas> の下に 1 行足す)
3434 <div class="stage">3535 <canvas id="canvas" width="800" height="600"></canvas>36 <div id="cursor"></div>3637 </div>3738 </body>3839</html>キャンバスを包んでいる .stage は 04 章から使っているものです。
ここに position: relative を足して、中の absolute がこの枠を基準に動くようにします。
style.css の .stage
43/* キャンバスを置く場所。上のバーを引いた残りの高さを、ここが全部使う */43/* キャンバスを置く場所。上のバーを引いた残りの高さを、ここが全部使う。44 position: relative にしておくと、中の absolute がこの枠を基準に動く。 */4445.stage {46 position: relative;4547 flex: 1;4648 /* flex の中身は既定では縮まないので、縮んでよいことを伝える */4749 min-height: 0;4850}style.css(canvas の下)
64/* 相手のペン先を表す丸。left / top は JavaScript から px で入れる。 */65#cursor {66 position: absolute;67 /* 中心を座標に合わせるため、自分の半分だけ左上にずらす */68 margin: -9px 0 0 -9px;69 width: 18px;70 height: 18px;71 border: 2px solid #222;72 border-radius: 50%;73 background: #ffd60a;74 /* 丸がクリックを横取りしないようにする */75 pointer-events: none;76 /* 相手が動くまでは出さない */77 display: none;78}pointer-events: none を忘れると、丸の下をなぞったときに線が途切れます。
丸がマウスの合図を横取りしてしまうからです。
部品を取り出す
Section titled “部品を取り出す”main.js の先頭
7const canvas = document.querySelector('#canvas');8const cursorMark = document.querySelector('#cursor');9const ctx = canvas.getContext('2d');main.js(draw の下)
123// ペン先の位置を相手に知らせる。pos が null なら「キャンバスの外に出た」。124// 絵ではないので draw を通さない。apply もしないし、history にも入れない。125function sendCursor(pos) {126 if (conn === null) return;127
128 conn.send({129 type: 'cursor',130 x: pos === null ? null : pos.x,131 y: pos === null ? null : pos.y,132 });133}conn.send を直接呼んでいるところがポイントです。
draw を呼ぶと、自分のキャンバスに描かれ、history にも貯まってしまいます。
main.js の apply
9091function apply(data) {9192 if (data.type === 'line') {9293 drawLine(data.x1, data.y1, data.x2, data.y2, data.color, data.width);9394 }9495 if (data.type === 'stamp') {9596 drawStamp(data.x, data.y, data.emoji);9697 }9798 if (data.type === 'clear') {9899 clearCanvas();99100 }101 if (data.type === 'cursor') {102 showCursor(data.x, data.y);103 }100104}main.js(sendCursor の下)
135// 相手のペン先を、キャンバスの上に重ねた丸で表す。136// 800x600 の中での座標に、いま表示しているキャンバスの大きさを掛けて画面の px に直す。137// キャンバスが縮んで表示されていてもズレない。138function showCursor(x, y) {139 if (x === null) {140 cursorMark.style.display = 'none';141 return;142 }143
144 cursorMark.style.display = 'block';145 cursorMark.style.left = (x / canvas.width) * canvas.clientWidth + 'px';146 cursorMark.style.top = (y / canvas.height) * canvas.clientHeight + 'px';147}canvas.width(800)ではなく canvas.clientWidth(いま画面に出ている幅)で掛けるのがコツです。
キャンバスは空いている場所に収まるまで縮んで表示されるので、
800 のまま計算すると、縮んだぶんだけ丸がズレます。
pointermove は、ボタンを押していなくてもマウスが動くたびに呼ばれます。
だから last === null で帰る前に送ります。
main.js の pointermove
167197canvas.addEventListener('pointermove', function (event) {168 if (last === null) return;169
170198 const pos = positionOf(event);171199
200 // 描いていないときも、ペン先の位置だけは送り続ける201 sendCursor(pos);202
203 if (last === null) return;204
172205 draw({173206 type: 'line',174207 x1: last.x,175208 y1: last.y,176209 x2: pos.x,177210 y2: pos.y,178211 // けしごむは「背景と同じ白い色で、太く描くペン」として作る179212 color: tool === 'eraser' ? '#ffffff' : color,180213 width: tool === 'eraser' ? 40 : 4,181214 });182215
183216 last = pos;184217});もとのコードは if (last === null) return; が先で positionOf があとでした。
順番を入れかえています。
main.js の pointerleave
223canvas.addEventListener('pointerleave', function () {224 // キャンバスから出たことを伝えて、相手の画面の丸を消してもらう225 sendCursor(null);226 last = null;227});これが無いと、相手がキャンバスから出たあとも丸が残り続けます。
2 つのプレビューをつないで、描かずにマウスを動かしてください。 もう片方に黄色い丸が付いてきます。
送りすぎに注意
Section titled “送りすぎに注意”pointermove は、速く動かすと 1 秒に何十回も呼ばれます。
いまは線を引くときも同じ回数だけ送っているので、通信量は倍くらいにしかなりません。
ただし線と違って、カーソルは描いていない間もずっと送り続けます。 気になるなら、前に送った時刻を覚えておいて「16 ミリ秒あけて送る」ようにすると、 だいたい 1 秒 60 回に抑えられます。
let lastSentAt = 0;
function sendCursor(pos) { if (conn === null) return;
const now = Date.now(); if (pos !== null && now - lastSentAt < 16) return; lastSentAt = now;
// …あとは同じ}「外に出た」の合図(pos === null)だけは、間引かずに必ず送ります。
これを落とすと、相手の画面に丸が残ってしまいます。
この節を終えたときのディレクトリ
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 id="cursor"></div> </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 cursorMark = document.querySelector('#cursor');const ctx = canvas.getContext('2d');
// つながった相手との通り道。まだつながっていないので null。let conn = null;
// いま選んでいる道具と色とスタンプlet tool = 'pen';let color = '#333333';let stamp = '🐱';
// これまでに描いた指示をぜんぶ覚えておくconst history = [];
// 画面の「あいことば」= ピア 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);
// 自分がこれまでに描いたものを送り直して、相手の画面にも同じ絵を出す。 // あとから入ってきた人にも、いまの絵が見えるようになる。 history.forEach(function (data) { conn.send(data); });}
// 指示のとおりにキャンバスへ描く。// 自分が出した指示も、相手から届いた指示も、かならずここを通る。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(); } if (data.type === 'cursor') { showCursor(data.x, data.y); }}
// 自分のキャンバスに描いてから、同じ指示を相手にも送る。// 「描く」と「送る」を必ずセットにするので、2 つの画面が同じ絵になる。function draw(data) { apply(data);
// 出した指示は覚えておく(あとから来た相手に送り直すため) if (data.type === 'clear') { history.length = 0; } else { history.push(data); }
if (conn) { conn.send(data); }}
// ペン先の位置を相手に知らせる。pos が null なら「キャンバスの外に出た」。// 絵ではないので draw を通さない。apply もしないし、history にも入れない。function sendCursor(pos) { if (conn === null) return;
conn.send({ type: 'cursor', x: pos === null ? null : pos.x, y: pos === null ? null : pos.y, });}
// 相手のペン先を、キャンバスの上に重ねた丸で表す。// 800x600 の中での座標に、いま表示しているキャンバスの大きさを掛けて画面の px に直す。// キャンバスが縮んで表示されていてもズレない。function showCursor(x, y) { if (x === null) { cursorMark.style.display = 'none'; return; }
cursorMark.style.display = 'block'; cursorMark.style.left = (x / canvas.width) * canvas.clientWidth + 'px'; cursorMark.style.top = (y / canvas.height) * canvas.clientHeight + 'px';}
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) { const pos = positionOf(event);
// 描いていないときも、ペン先の位置だけは送り続ける sendCursor(pos);
if (last === null) return;
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 () { // キャンバスから出たことを伝えて、相手の画面の丸を消してもらう sendCursor(null); 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;}
/* キャンバスを置く場所。上のバーを引いた残りの高さを、ここが全部使う。 position: relative にしておくと、中の absolute がこの枠を基準に動く。 */.stage { position: relative; flex: 1; /* flex の中身は既定では縮まないので、縮んでよいことを伝える */ min-height: 0;}
canvas { display: block; background: #fff; border-radius: 8px; /* 実際の解像度は 800x600 のまま、あいている場所に収まる大きさで表示する。 こうすると、どの端末でも同じ座標で絵を共有できて、画面もスクロールしない。 */ max-width: 100%; max-height: 100%; /* 指でなぞったときにページがスクロールしないようにする(スマホ用) */ touch-action: none;}
/* 相手のペン先を表す丸。left / top は JavaScript から px で入れる。 */#cursor { position: absolute; /* 中心を座標に合わせるため、自分の半分だけ左上にずらす */ margin: -9px 0 0 -9px; width: 18px; height: 18px; border: 2px solid #222; border-radius: 50%; background: #ffd60a; /* 丸がクリックを横取りしないようにする */ pointer-events: none; /* 相手が動くまでは出さない */ display: none;}