public void Configuration(IAppBuilder app){ app.MapSignalR();}
建立DrawingHub
public class Drawing : Hub{ private const int BoardWidth = 300, BoardHeight = 300; private static int[,] _buffer = new int[BoardWidth, BoardHeight]; public Task BroadcastPoint(int x, int y) { if (x < 0) x = 0; if (x >= BoardWidth) x = BoardWidth - 1; if (y < 0) y = 0; if (y >= BoardHeight) y = BoardHeight - 1; int color = 0; int.TryParse(Clients.Caller.color, out color); _buffer[x, y] = color; return Clients.Others.DrawPoint(x, y, Clients.Caller.color); } public Task BroadcastClear() { _buffer = new int[BoardWidth, BoardHeight]; return Clients.Others.Clear(); } public override Task OnConnected() { return Clients.Caller.Update(_buffer); }}
用一个二位数组来缓存画板,一共就三个方法
当客户端连接时调用Update()方法刷新整个画板
BroadcastClear()是点击清除按钮时讲整个画板擦出
最后一个就是画画方法,客户端按下鼠标画画时,调用该方法进行绘制。
页面
Drawing board
页面非常简单,一个选择颜色的下拉框,一个画板,和一个清除按钮。
javascript
$(function () {//初始化 var colors = ["black", "red", "green", "blue", "yellow", "magenta", "white"]; var canvas = $("#canvas"); var colorElement = $("#color"); for (var i = 0; i < colors.length; i++) { colorElement.append( "