Permalink
Browse files

Added channel for drawing events.

The Javascript code now only draws in response to a message on the channel.
In response to an input event, the Javascript code now sends draw events to be broadcast to all listeners (including itself).
  • Loading branch information...
michaeljbishop committed Oct 19, 2016
1 parent d5fcc37 commit daf5436d34b627d91133f3a85ea50fc25b5f4e33
Showing with 32 additions and 8 deletions.
  1. +15 −0 web/channels/room_channel.ex
  2. +1 −1 web/channels/user_socket.ex
  3. +16 −2 web/static/js/app.js
  4. +0 −5 web/static/js/socket.js
@@ -0,0 +1,15 @@
+defmodule Draw.RoomChannel do
+ use Phoenix.Channel
+
+ def join("room:drawing", _message, socket) do
+ {:ok, socket}
+ end
+ def join("room:" <> _private_room_id, _params, _socket) do
+ {:error, %{reason: "unauthorized"}}
+ end
+
+ def handle_in("drawLine", %{"line" => line} = params, socket) do
+ broadcast! socket, "drawLine", %{line: line}
+ {:noreply, socket}
+ end
+end
@@ -2,7 +2,7 @@ defmodule Draw.UserSocket do
use Phoenix.Socket
## Channels
- # channel "room:*", Draw.RoomChannel
+ channel "room:*", Draw.RoomChannel
## Transports
transport :websocket, Phoenix.Transports.WebSocket
View
@@ -18,16 +18,30 @@ import "phoenix_html"
// Local files can be imported directly using relative
// paths "./socket" or full ones "web/static/js/socket".
-// import socket from "./socket"
+import socket from "./socket"
+
+let channel = socket.channel("room:drawing", {})
+channel.join()
+ .receive("ok", resp => { console.log("Joined successfully", resp) })
+ .receive("error", resp => { console.log("Unable to join", resp) })
var canvas = document.getElementById("draw-canvas");
var ctx = canvas.getContext("2d");
function drawLine(from, to) {
+ // Send a message to draw a line (we'll draw when we receive it)
+ channel.push("drawLine", {line: [from, to]})
+}
+
+// Draw whatever we receive
+channel.on("drawLine", payload => {
+ var from = payload.line[0];
+ var to = payload.line[1];
ctx.moveTo(from.x, from.y);
ctx.lineTo(to.x, to.y);
ctx.stroke();
-}
+})
+
// ------------------------
// General Input Tracking
View
@@ -54,9 +54,4 @@ let socket = new Socket("/socket", {params: {token: window.userToken}})
socket.connect()
// Now that you are connected, you can join channels with a topic:
-let channel = socket.channel("topic:subtopic", {})
-channel.join()
- .receive("ok", resp => { console.log("Joined successfully", resp) })
- .receive("error", resp => { console.log("Unable to join", resp) })
-
export default socket

0 comments on commit daf5436

Please sign in to comment.