Created
December 22, 2011 19:55
-
-
Save sectore/1511618 to your computer and use it in GitHub Desktop.
Client-side Roundtrip to send and receive (binary) image data using Socket.IO
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### | |
1 SENDING DATA | |
1.1 get original image data clicking on it | |
1.2 get its base64-encoded data | |
1.3 emit the data by Socket.IO to server (Node.js) | |
### | |
$(".my-image").click (event) => | |
# get image which was clicked | |
img = event.target | |
# create base64 encoded image | |
imgdata = @getBase64Image(img) | |
# emit data to clients | |
@socket.emit 'onimgdata', { width: img.width, height: img.height, source:imgdata } | |
### | |
Helper method to get a base64 encoded image data | |
Based on http://stackoverflow.com/questions/934012/get-image-data-in-javascript | |
### | |
getBase64Image:(img) -> | |
# create canvas | |
canvas = document.createElement "canvas" | |
canvas.width = img.width | |
canvas.height = img.height | |
context = canvas.getContext "2d" | |
# draw image into canvas | |
context.drawImage img, | |
0, | |
0 | |
### | |
Get the data-URL formatted image | |
using jpeg format as the type of the image to be returned | |
@see: http://www.w3.org/TR/html5/the-canvas-element.html | |
### | |
data = canvas.toDataURL "image/jpeg" | |
#return data | |
data | |
### | |
2 RECEIVING DATA + DISPLAY IMAGE | |
2.1 listen to "showimgdata" event sent from server (Node.js) | |
2.2 push data to HTML image | |
### | |
@socket.on 'showimgdata', (data) -> | |
#get image | |
img = $('#show-img').get 0 | |
message | |
try | |
# set data for image | |
img.width = data.width; | |
img.height = data.height; | |
img.src = data.source; | |
message = '' | |
catch error | |
console.log error | |
message = 'error receiving image data...' | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment