色を変える
いまの線は黒(#333333)で決め打ちです。色を選べるようにします。
短い節ですが、色を送る側が決めるのか、受け取る側が決めるのかという リアルタイム共有の考えどころが出てきます。
今回さわる
app/:index.htmlに色ボタン、style.cssに色ボタンの見た目、main.jsに選んだ色を覚える処理
前の節を終えていない人は、ここから始められます。
色ボタンを足す
Section titled “色ボタンを足す”index.html の .tools の中(ペンとスタンプのあいだ)
22<button class="color selected" data-color="#333333"></button>23<button class="color" data-color="#e5484d"></button>24<button class="color" data-color="#f5a524"></button>25<button class="color" data-color="#17c964"></button>26<button class="color" data-color="#006fee"></button>2127<button class="stamp" data-stamp="🐱">🐱</button>ボタンの中身は空です。見た目の色は data-color から JavaScript で流し込みます。
こうしておくと、色を増やしたいとき HTML に 1 行足すだけで済みます。
CSS に .color-red { background: ... } のような定義を増やす必要がありません。
色ボタンの形を整える
Section titled “色ボタンの形を整える”style.css を変更する
Section titled “style.css を変更する”style.css(input, button { ... } の下)
2626 padding: 6px 10px;2727}2828
29.color {30 width: 32px;31 height: 32px;32 padding: 0;33 border: 2px solid #fff;34 border-radius: 50%;35 /* 色そのものは data-color から JavaScript で流し込む */36}37
2938/* いま選んでいる道具・色が分かるようにする */3039.selected {3140 outline: 3px solid #ffd60a;いま選んでいる色を覚える
Section titled “いま選んでいる色を覚える”main.js(道具の状態のところ)
12// いま選んでいる道具とスタンプ12// いま選んでいる道具と色とスタンプ1313let tool = 'pen';14let color = '#333333';1415let stamp = '🐱';決め打ちをやめる
Section titled “決め打ちをやめる”main.js の pointermove の中
151152draw({152153 type: 'line',153154 x1: last.x,154155 y1: last.y,155156 x2: pos.x,156157 y2: pos.y,157 color: '#333333',158 color: color,158159 width: 4,159160});色ボタンを押せるようにする
Section titled “色ボタンを押せるようにする”main.js(.stamp のループの下、select の上)
188document.querySelectorAll('.color').forEach(function (button) {189 // ボタンの見た目の色を data-color から流し込む190 button.style.background = button.dataset.color;191
192 button.addEventListener('click', function () {193 color = button.dataset.color;194 select(button, '.color');195 });196});select(button, '.color') の第 2 引数が '.color' だけなのに注目してください。
色は道具とは別のグループです。「ペンを選んでいる」と「赤を選んでいる」は同時に成り立つので、
選択の印を外し合う相手も別になります。
色は「送る側」が決める
Section titled “色は「送る側」が決める”ここが今回の考えどころです。
送っているのはこういう指示でした。
{ type: 'line', x1: ..., y1: ..., x2: ..., y2: ..., color: '#e5484d', width: 4 }color が指示の中に入っています。つまり 描いた人が選んだ色が、そのまま相手の画面でも使われます。
もし color を送らず、受け取り側が自分の color を使ったらどうなるでしょう。
相手が青を選んでいれば、こちらが赤で描いた線が相手の画面では青になります。
同じ絵を見ているつもりが、実は違うものを見ていることになります。
図: 「見た目に必要な情報は、すべて指示に入れる」。
一方、送らないほうがいい情報もあります。たとえば「いまペンを選んでいる」という状態です。 それは自分の手元の話で、相手の画面には関係ありません。
- 絵に残るもの(座標・色・太さ・スタンプの絵柄)… 指示に入れて送る
- 手元の状態(選択中の道具、選択中の色そのもの)… 送らない
色を選んでから線を引くと、相手の画面にも同じ色で出ます。 2 つのプレビューで別々の色を選んで、交互に描いてみてください。
この節を終えたときのディレクトリ
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="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: color, width: 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;}