Permalink
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
56 lines (49 sloc) 1.36 KB
<!DOCTYPE html>
<meta charset="utf-8" />
<title>Websocket Canvas</title>
<script language="javascript" type="text/javascript">
var wsUri = "ws://localhost:1234/ws";
var ctx;
function wsConnect()
{
var canvas = document.getElementById( "canvas" );
ctx = canvas.getContext( '2d' );
ws = new WebSocket( wsUri );
ws.onopen = function( e ) {
console.log( "CONNECTED" );
ws.send( "READY" );
};
ws.onclose = function( e ) {
console.log( "DISCONNECTED" );
};
ws.onmessage = function( e ) {
var data = e.data.split("\n");
for ( var line in data ) {
var msg = data[line].split(" ");
var cmd = msg[0];
if ( cmd == "CLEAR" ) {
ctx.clearRect( 0, 0, 512, 512 );
} else if ( cmd == "PIXEL" ) {
var x = parseInt(msg[1]);
var y = parseInt(msg[2]);
var color = msg[3];
ctx.fillStyle = color;
ctx.fillRect( x, y, 1, 1 );
} else {
console.log( "Unknown command: " + cmd );
}
}
};
ws.onerror = function( e ) {
console.log( 'WS Error: ' + e.data );
};
}
window.addEventListener( "load", wsConnect, false );
</script>
<body>
<h2>Websocket Canvas</h2>
<canvas id="canvas" width="512" height="512">
Sorry, your browser does not support Canvas
</canvas>
</body>
</html>