I'm trying to use a mouse:down event on canvas like:
canvas.on('mouse:down', function(options) {}
How can I use touchstart event handler?
I hope this helps
// TOUCH EVENTS
canvas.addEventListener("touchstart", function (e) {
e.preventDefault();
var mousePos = getTouchPos(canvas, e);
var touch = e.touches[0];
// do_mouse_click_logic(mousePos.x, mousePos.y, touch.clientX, touch.clientY);
}, false);
canvas.addEventListener("touchend", function (e) {
e.preventDefault();
var mousePos = getTouchPos(canvas, e);
// do_mouse_up_logic(mousePos.x, mousePos.y);
}, false);
canvas.addEventListener("touchmove", function (e) {
e.preventDefault();
var mousePos = getTouchPos(canvas, e);
var touch = e.touches[0];
// do_mouse_move_logic(mousePos.x, mousePos.y, touch.clientX, touch.clientY);
}, false);
function getTouchPos(canvasDom, touchEvent) {
var rect = canvasDom.getBoundingClientRect();
return {
x: touchEvent.touches[0].clientX - rect.left,
y: touchEvent.touches[0].clientY - rect.top
};
}
// MOUSE EVENTS
canvas.addEventListener('mousedown', function(evt) {
evt.preventDefault();
var mousepos = get_mouse_pos(canvas, evt);
// do_mouse_click_logic(mousepos.x, mousepos.y, evt.pageX, evt.pageY);
}, false);
canvas.addEventListener('mousemove', function(evt) {
evt.preventDefault();
var mousepos = get_mouse_pos(canvas, evt);
// do_mouse_move_logic(mousepos.x, mousepos.y, evt.pageX, evt.pageY);
});
canvas.addEventListener('mouseup', function(evt) {
evt.preventDefault();
var mousepos = get_mouse_pos(canvas, evt);
// do_mouse_up_logic(mousepos.x, mousepos.y);
}, false);
function get_mouse_pos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
function do_mouse_click_logic(x, y, page_x, page_y) {
// Do your stuff
}
function do_mouse_move_logic(x, y, page_x, page_y) {
// Do your stuff
}
function do_mouse_up_logic(x, y) {
// Do yuor stuff
}
Related
I have got problem with webRTC screen sharing. When one person shares his screen another person can`t see shared screen stream, and asks him for again sharing screen.I am useing node.js express server with socket.io. I am useing Google chrome. It requires HTTPS connection if it is not local.
This is web application code`
(function() {
const socket = io.connect(window.location.origin);
const localVideo = document.querySelector('.localVideo');
const remoteVideos = document.querySelector('.remoteVideos');
const peerConnections = {};
var url_string =window.location.href
var url = new URL(url_string);
var de = url.searchParams.get("key");
let room = de
let getUserMediaAttempts = 5;
let gettingUserMedia = false;
let getdisplaymedia=true;
const config = {
'iceServers': [{
'urls': ['stun:stun.l.google.com:19302']
}]
};
/** #type {MediaStreamConstraints} */
const constraints = {
audio: true,
video: { facingMode: "user" }
};
socket.on('bye', function(id) {
handleRemoteHangup(id);
});
if (room && !!room) {
socket.emit('join', room);
}
window.onunload = window.onbeforeunload = function() {
socket.close();
};
socket.on('ready', function (id) {
if (!(localVideo instanceof HTMLVideoElement) || !localVideo.srcObject) {
return;
}
const peerConnection = new RTCPeerConnection(config);
peerConnections[id] = peerConnection;
if (localVideo instanceof HTMLVideoElement) {
peerConnection.addStream(localVideo.srcObject);
}
peerConnection.createOffer()
.then(sdp => peerConnection.setLocalDescription(sdp))
.then(function () {
socket.emit('offer', id, peerConnection.localDescription);
});
peerConnection.onaddstream = event => handleRemoteStreamAdded(event.stream, id);
peerConnection.onicecandidate = function(event) {
if (event.candidate) {
socket.emit('candidate', id, event.candidate);
}
};
});
socket.on('offer', function(id, description) {
const peerConnection = new RTCPeerConnection(config);
peerConnections[id] = peerConnection;
if (localVideo instanceof HTMLVideoElement) {
peerConnection.addStream(localVideo.srcObject);
}
peerConnection.setRemoteDescription(description)
.then(() => peerConnection.createAnswer())
.then(sdp => peerConnection.setLocalDescription(sdp))
.then(function () {
socket.emit('answer', id, peerConnection.localDescription);
});
peerConnection.onaddstream = event => handleRemoteStreamAdded(event.stream, id);
peerConnection.onicecandidate = function(event) {
if (event.candidate) {
socket.emit('candidate', id, event.candidate);
}
};
});
socket.on('candidate', function(id, candidate) {
peerConnections[id].addIceCandidate(new RTCIceCandidate(candidate))
.catch(e => console.error(e));
});
socket.on('answer', function(id, description) {
peerConnections[id].setRemoteDescription(description);
});
function getUserMediaSuccess(stream) {
gettingUserMedia = false;
if (localVideo instanceof HTMLVideoElement) {
!localVideo.srcObject && (localVideo.srcObject = stream);
}
socket.emit('ready');
}
function handleRemoteStreamAdded(stream, id) {
const remoteVideo = document.createElement('video');
remoteVideo.srcObject = stream;
remoteVideo.setAttribute("id", id.replace(/[^a-zA-Z]+/g, "").toLowerCase());
remoteVideo.setAttribute("playsinline", "true");
remoteVideo.setAttribute("autoplay", "true");
remoteVideos.appendChild(remoteVideo);
if (remoteVideos.querySelectorAll("video").length === 1) {
remoteVideos.setAttribute("class", "one remoteVideos");
} else {
remoteVideos.setAttribute("class", "remoteVideos");
}
}
function getUserMediaError(error) {
console.error(error);
gettingUserMedia = false;
(--getUserMediaAttempts > 0) && setTimeout(getUserMediaDevices, 1000);
}
function getUserMediaDevices() {
if (localVideo instanceof HTMLVideoElement) {
if (localVideo.srcObject) {
getUserMediaSuccess(localVideo.srcObject);
} else if (!gettingUserMedia && !localVideo.srcObject) {
gettingUserMedia = true;
navigator.mediaDevices.getDisplayMedia(constraints)
.then(getUserMediaSuccess)
.catch(getUserMediaError);
}
}
}
function handleRemoteHangup(id) {
peerConnections[id] && peerConnections[id].close();
delete peerConnections[id];
document.querySelector("#" + id.replace(/[^a-zA-Z]+/g, "").toLowerCase()).remove();
if (remoteVideos.querySelectorAll("video").length === 1) {
remoteVideos.setAttribute("class", "one remoteVideos");
} else {
remoteVideos.setAttribute("class", "remoteVideos");
}
}
getUserMediaDevices();
})();
This is node.js code`
const credentials = require('./credentials');
const express = require('express');
const app = express();
let server;
let port;
if (credentials.key && credentials.cert) {
const https = require('https');
server = https.createServer(credentials, app);
port = 443;
} else {
const http = require('http');
server = http.createServer(app);
port = 1517;
}
const io = require('socket.io')(server);
const RoomService = require('./RoomService')(io);
io.sockets.on('connection', RoomService.listen);
io.sockets.on('error', e => console.log(e));
app.use(express.static(__dirname + '/public'));
app.get('*', function(req, res) {
res.sendFile(${__dirname}/public/index.html);
});
server.listen(port, () => console.log(Server is running on port ${port}));
ok man this is fixed code you can use yuu need just stream getDisplayMedia value
(function() {
const socket = io.connect(window.location.origin);
const localVideo = document.querySelector('.localVideo');
const remoteVideos = document.querySelector('.remoteVideos');
const peerConnections = {};
var url_string =window.location.href
var url = new URL(url_string);
var de = url.searchParams.get("key");
let room = de
let getUserMediaAttempts = 5;
let gettingUserMedia = false;
let getdisplaymedia=true;
/** #type {RTCConfiguration} */
const config = {
'iceServers': [{
'urls': ['stun:stun.l.google.com:19302']
}]
};
/** #type {MediaStreamConstraints} */
const constraints = {
audio: true,
video: { facingMode: "user" }
};
socket.on('full', function(room) {
alert('Room ' + room + ' is full');
});
socket.on('bye', function(id) {
handleRemoteHangup(id);
});
if (room && !!room) {
socket.emit('join', room);
}
window.onunload = window.onbeforeunload = function() {
socket.close();
};
socket.on('ready', function (id) {
if (!(localVideo instanceof HTMLVideoElement) || !localVideo.srcObject) {
return;
}
const peerConnection = new RTCPeerConnection(config);
peerConnections[id] = peerConnection;
if (localVideo instanceof HTMLVideoElement) {
peerConnection.addStream(localVideo.srcObject);
}
peerConnection.createOffer()
.then(sdp => peerConnection.setLocalDescription(sdp))
.then(function () {
socket.emit('offer', id, peerConnection.localDescription);
});
peerConnection.onaddstream = event => handleRemoteStreamAdded(event.stream, id);
peerConnection.onicecandidate = function(event) {
if (event.candidate) {
socket.emit('candidate', id, event.candidate);
}
};
});
socket.on('offer', function(id, description) {
const peerConnection = new RTCPeerConnection(config);
peerConnections[id] = peerConnection;
if (localVideo instanceof HTMLVideoElement) {
peerConnection.addStream(localVideo.srcObject);
}
peerConnection.setRemoteDescription(description)
.then(() => peerConnection.createAnswer())
.then(sdp => peerConnection.setLocalDescription(sdp))
.then(function () {
socket.emit('answer', id, peerConnection.localDescription);
});
peerConnection.onaddstream = event => handleRemoteStreamAdded(event.stream, id);
peerConnection.onicecandidate = function(event) {
if (event.candidate) {
socket.emit('candidate', id, event.candidate);
}
};
});
socket.on('candidate', function(id, candidate) {
peerConnections[id].addIceCandidate(new RTCIceCandidate(candidate))
.catch(e => console.error(e));
});
socket.on('answer', function(id, description) {
peerConnections[id].setRemoteDescription(description);
});
function getUserMediaSuccess(stream) {
gettingUserMedia = false;
if (localVideo instanceof HTMLVideoElement) {
!localVideo.srcObject && (localVideo.srcObject = stream);
}
socket.emit('ready');
}
function handleRemoteStreamAdded(stream, id) {
const remoteVideo = document.createElement('video');
remoteVideo.srcObject = stream;
remoteVideo.setAttribute("id", id.replace(/[^a-zA-Z]+/g, "").toLowerCase());
remoteVideo.setAttribute("playsinline", "true");
remoteVideo.setAttribute("autoplay", "true");
remoteVideos.appendChild(remoteVideo);
if (remoteVideos.querySelectorAll("video").length === 1) {
remoteVideos.setAttribute("class", "one remoteVideos");
} else {
remoteVideos.setAttribute("class", "remoteVideos");
}
}
function getUserMediaError(error) {
console.error(error);
gettingUserMedia = false;
(--getUserMediaAttempts > 0) && setTimeout(getUserMediaDevices, 1000);
}
function getUserMediaDevices() {
var constraints = { audio: true, video: { width: 1280, height: 720 } };
navigator.mediaDevices.getDisplayMedia(constraints)
.then(function(mediaStream) {
var video = document.querySelector('video');
video.srcObject = mediaStream;
video.onloadedmetadata = function(e) {
video.play();
getUserMediaSuccess(video.srcObject)
};
})
.catch(function(err) { console.log(err.name + ": " + err.message); }); // always check for errors at the end.
}
function handleRemoteHangup(id) {
peerConnections[id] && peerConnections[id].close();
delete peerConnections[id];
document.querySelector("#" + id.replace(/[^a-zA-Z]+/g, "").toLowerCase()).remove();
if (remoteVideos.querySelectorAll("video").length === 1) {
remoteVideos.setAttribute("class", "one remoteVideos");
} else {
remoteVideos.setAttribute("class", "remoteVideos");
}
}
getUserMediaDevices();
})();
I'm trying to add AnalyserNode and visualize the output sound to a web audio example that I made but I can't figure out how. I think I am not passing the right source to the analyser (?)
Here for the full code : https://jsfiddle.net/kepin95043/1ub0sjo3/
<script>
var fs = 2000;
var gain = 0.2;
class Sound {
constructor(context) {
this.context = context;
}
init() {
this.oscillator = this.context.createOscillator();
this.oscillator.frequency.value = fs;
this.gainNode = this.context.createGain();
this.oscillator.connect(this.gainNode);
this.gainNode.connect(this.context.destination);
}
play(value) {
this.init();
this.gainNode.gain.setValueAtTime(gain, this.context.currentTime);
this.oscillator.start();
}
stop() {
this.gainNode.gain.exponentialRampToValueAtTime(0.001, this.context.currentTime + 1);
this.oscillator.stop(this.context.currentTime + 1);
}
}
var context = new AudioContext();
var sound = new Sound(context);
sound.init();
var wave = 'sine';
var state = 'paused';
var waveSelectors = document.querySelectorAll('.waveform');
var playBtn = document.querySelector('#play');
var container = document.querySelector('.container');
waveSelectors.forEach(function(button) {
button.addEventListener('click', function() {
cleanClass('active');
wave = button.dataset.wave;
sound.oscillator.type = wave;
button.classList.add('active');
})
})
playBtn.addEventListener('click', function() {
context.resume().then(() => {
console.log('Playback resumed successfully');
});
if (playBtn.text == 'Play') {
sound.play();
sound.oscillator.type = wave;
playBtn.text = 'Pause';
} else {
sound.stop();
playBtn.text = 'Play';
}
})
function cleanClass(rclass) {
waveSelectors.forEach(function(button) {
button.classList.remove(rclass);
})
}
function changeFs(val) {
fs = val;
var output = document.getElementById("fsValue");
output.innerHTML = val;
sound.stop();
sound.play();
console.log(val);
};
function changeGain(val) {
gain = val;
var output = document.getElementById("gainValue");
output.innerHTML = val;
sound.stop();
sound.play();
console.log(val);
};
var masterGain;
masterGain = context.createGain();
masterGain.connect(context.destination);
// analyser
var analyser = context.createAnalyser();
masterGain.connect(analyser);
var waveform = new Float32Array(analyser.frequencyBinCount);
analyser.getFloatTimeDomainData(waveform);
(function updateWaveform() {
requestAnimationFrame(updateWaveform);
analyser.getFloatTimeDomainData(waveform);
}());
var spectrum = new Uint8Array(analyser.frequencyBinCount);
(function updateSpectrum() {
requestAnimationFrame(updateSpectrum);
analyser.getByteFrequencyData(spectrum);
}());
// oscilloscope
var scopeCanvas = document.getElementById('canvas');
scopeCanvas.width = waveform.length;
//scopeCanvas.height = 200;
scopeCanvas.height = scopeCanvas.width * 0.33;
var scopeContext = scopeCanvas.getContext('2d');
(function drawOscilloscope() {
requestAnimationFrame(drawOscilloscope);
scopeContext.clearRect(0, 0, scopeCanvas.width, scopeCanvas.height);
scopeContext.strokeStyle="white"; // Green path
scopeContext.beginPath();
for (var i = 0; i < waveform.length; i++) {
var x = i;
var y = (0.5 + waveform[i] / 2) * scopeCanvas.height;
if (i === 0) {
scopeContext.moveTo(x, y);
} else {
scopeContext.lineTo(x, y);
}
}
scopeContext.stroke();
}());
</script>
Could anyone help me to identify what I'm doing wrong?
Thank in advance!
PS: Open it with Firefox. Does not work on Chromium based browsers for me.
Here is a working example: https://codepen.io/dennisgaebel/pen/YEwLaL
You create a Sound object and also a masterGain that is connected to your AnalyserNode. But I don't see where the sound ever connects to the masterGain. Without that, your analyser node just gets silence.
Here is the full working script code:
var fs = 2000;
var gain = 0.2;
class Sound {
constructor(context) {
this.context = context;
}
init() {
this.oscillator = this.context.createOscillator();
this.oscillator.frequency.value = fs;
this.gainNode = this.context.createGain();
this.oscillator.connect(this.gainNode);
this.gainNode.connect(this.context.destination);
}
play(value) {
this.init();
this.gainNode.gain.setValueAtTime(gain, this.context.currentTime);
this.oscillator.start();
// connect analyser to the gainedSource
this.gainNode.connect(analyser);
// for the non gainedSource
//this.gainNode.connect(analyser);
}
stop() {
this.gainNode.gain.exponentialRampToValueAtTime(0.001, this.context.currentTime + 1);
this.oscillator.stop(this.context.currentTime + 1);
}
}
var context = new AudioContext();
var sound = new Sound(context);
sound.init();
var wave = 'sine';
var state = 'paused';
var waveSelectors = document.querySelectorAll('.waveform');
var playBtn = document.querySelector('#play');
var container = document.querySelector('.container');
waveSelectors.forEach(function(button) {
button.addEventListener('click', function() {
cleanClass('active');
wave = button.dataset.wave;
sound.oscillator.type = wave;
button.classList.add('active');
})
})
playBtn.addEventListener('click', function() {
context.resume().then(() => {
console.log('Playback resumed successfully');
});
if (playBtn.text == 'Play') {
sound.play();
sound.oscillator.type = wave;
playBtn.text = 'Pause';
} else {
sound.stop();
playBtn.text = 'Play';
}
})
function cleanClass(rclass) {
waveSelectors.forEach(function(button) {
button.classList.remove(rclass);
})
}
function changeFs(val) {
fs = val;
var output = document.getElementById("fsValue");
output.innerHTML = val;
sound.stop();
sound.play();
console.log(val);
};
function changeGain(val) {
gain = val;
var output = document.getElementById("gainValue");
output.innerHTML = val;
sound.stop();
sound.play();
console.log(val);
};
// analyser node
var analyser = context.createAnalyser();
var waveform = new Float32Array(analyser.frequencyBinCount);
analyser.getFloatTimeDomainData(waveform);
(function updateWaveform() {
requestAnimationFrame(updateWaveform);
analyser.getFloatTimeDomainData(waveform);
}());
var spectrum = new Uint8Array(analyser.frequencyBinCount);
(function updateSpectrum() {
requestAnimationFrame(updateSpectrum);
analyser.getByteFrequencyData(spectrum);
}());
// oscilloscope
var scopeCanvas = document.getElementById('canvas');
scopeCanvas.width = waveform.length;
scopeCanvas.height = scopeCanvas.width * 0.33;
var scopeContext = scopeCanvas.getContext('2d');
(function drawOscilloscope() {
requestAnimationFrame(drawOscilloscope);
scopeContext.clearRect(0, 0, scopeCanvas.width, scopeCanvas.height);
scopeContext.strokeStyle = "white"; // Green path
scopeContext.beginPath();
for (var i = 0; i < waveform.length; i++) {
var x = i;
var y = (0.5 + waveform[i] / 2) * scopeCanvas.height;
if (i === 0) {
scopeContext.moveTo(x, y);
} else {
scopeContext.lineTo(x, y);
}
}
scopeContext.stroke();
}());
I found this simple horizontal scroll :
http://jsfiddle.net/Lpjj3n1e/
Its working fine, but if I duplicate the horizontal scroll, only the first scroll function well.
What can I do to the JavaScript to be applied on 2, 3 or any variable number of generated scrolls ?
$(function() {
var print = function(msg) {
alert(msg);
};
var setInvisible = function(elem) {
elem.css('visibility', 'hidden');
};
var setVisible = function(elem) {
elem.css('visibility', 'visible');
};
var elem = $("#elem");
var items = elem.children();
// Inserting Buttons
elem.prepend('<div id="right-button" style="visibility: hidden;"><</div>');
elem.append(' <div id="left-button">></div>');
// Inserting Inner
items.wrapAll('<div id="inner" />');
// Inserting Outer
debugger;
elem.find('#inner').wrap('<div id="outer"/>');
var outer = $('#outer');
var updateUI = function() {
var maxWidth = outer.outerWidth(true);
var actualWidth = 0;
$.each($('#inner >'), function(i, item) {
actualWidth += $(item).outerWidth(true);
});
if (actualWidth <= maxWidth) {
setVisible($('#left-button'));
}
};
updateUI();
$('#right-button').click(function() {
var leftPos = outer.scrollLeft();
outer.animate({
scrollLeft: leftPos - 200
}, 800, function() {
debugger;
if ($('#outer').scrollLeft() <= 0) {
setInvisible($('#right-button'));
}
});
});
$('#left-button').click(function() {
setVisible($('#right-button'));
var leftPos = outer.scrollLeft();
outer.animate({
scrollLeft: leftPos + 200
}, 800);
});
$(window).resize(function() {
updateUI();
});
});
I'm trying to build a multiplayer card game using node.js and socket.io, i need to add players and give them a deck , how can i do that
server.js
var player = require("./players");
var nicknames=[];
io.on("connection", function (socket) {
socket.on('new user', function(data, callback){
if (nicknames.indexOf(data) != -1){
callback(false);
} else{
callback(true);
var aa = {id: nicknames.indexOf(data), name: data};
var ply = player(aa);
socket.user = data;
nicknames.push(socket.user);
updateNicknames();
}
});
function updateNicknames(){
io.sockets.emit('usernames', nicknames);
}
});
players.js
var Player = function(){
this.data ={
id : null,
name : null,
hand : []
};
this.fill = function (info) {
for(var prop in this.data) {
if(this.data[prop] !== 'undefined') {
this.data[prop] = info[prop];
}
}
};
this.getInformation = function () {
return this.data;
};
};
module.exports = function () {
var instance = new Player();
return instance;
};
but the program gives me in empty player object
This would be a good case for a constructor. If you use one, you'll want to avoid exporting an instantiated object. Consider the below players.js
var Player = (function() {
function Player(data) {
this.data = data;
var defaults = {
id: null,
name: null,
hand: []
};
for (var key in defaults) {
var val = defaults[key];
if (this.data[key] == null) {
this.data[key] = val;
}
}
}
Player.prototype.getData = function() {
return this.data;
};
return Player;
})();
module.exports = Player;
Then you can create a new instance of the Player class using the new operator.
var aa = {id: 0, name: 'test'};
var ply = new Player(aa);
console.log(ply.getData());
>> { id: 0, name: 'test', hand: [] }
I made a draw app in node.js and socket.io recently. It works fine but all things drawn by a user will be seen by all users. I want to add the concept of sessions so the things a user draws will only be seen by people in the same session. How can I do it?
Here's the server code I use:
var express = require('express');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(8000);
app.use(express.static(__dirname));
app.use(express.logger());
app.engine('html', require('ejs').__express);
app.get('/',function(req,res){
res.sendfile(__dirname+'/index.html');
});
io.sockets.on('connection',function(socket){
socket.on('mousedown',function(data){
socket.broadcast.emit('mousedown',data);
});
socket.on('mousemove',function(data){
socket.broadcast.emit('mousedown',data);
});
socket.on('mouseup',function(data){
socket.broadcast.emit('mousedown',data);
});
socket.on('tool',function(data){
socket.broadcast.emit('mousedown',data);
});
});
Also, this is the code I used for the clinet side:
var socket = {};
if(typeof io !== 'undefined' && io){
socket = io.connect('http://127.0.0.1:8000');
}
else
{
socket = {
emit:function(){
console.log(arguments);
},
on:function(){
console.log(arguments);
}
};
}
$(function(){
var canvas, context, canvaso, contexto;
// The active tool instance.
var tool;
var tool_default = 'line';
function init () {
// Find the canvas element.
canvaso = document.getElementById('imageView');
canvaso.width = window.innerWidth * 0.9;
canvaso.height = window.innerHeight/2;
if (!canvaso) {
console.log('Error: I cannot find the canvas element!');
return;
}
if (!canvaso.getContext) {
console.log('Error: no canvas.getContext!');
return;
}
// Get the 2D canvas context.
contexto = canvaso.getContext('2d');
if (!contexto) {
console.log('Error: failed to getContext!');
return;
}
// Add the temporary canvas.
var container = canvaso.parentNode;
canvas = document.createElement('canvas');
if (!canvas) {
console.log('Error: I cannot create a new canvas element!');
return;
}
canvas.id = 'imageTemp';
canvas.width = canvaso.width;
canvas.height = canvaso.height;
container.appendChild(canvas);
context = canvas.getContext('2d');
// Get the tool select input.
var tool_select = document.getElementById('dtool');
if (!tool_select) {
console.log('Error: failed to get the dtool element!');
return;
}
tool_select.addEventListener('change', ev_tool_change, false);
// Activate the default tool.
if (tools[tool_default]) {
tool = new tools[tool_default]();
tool_select.value = tool_default;
}
// Attach the mousedown, mousemove and mouseup event listeners.
$(canvas).on('mousedown',ev_canvas);
$(canvas).on('mousemove',ev_canvas);
$(canvas).on('mouseup',ev_canvas);
}
// The general-purpose event handler. This function just determines the mouse
// position relative to the canvas element.
function ev_canvas (ev) {
ev._x = ev.offsetX;
ev._y = ev.offsetY;
// Call the event handler of the tool.
var func = tool[ev.type];
socket.emit(ev.type,{x:ev._x,y:ev._y});
if (func) {
func(ev);
}
}
socket.on('mousedown',function(data){
ev_canvas({type:'mousedown',_x:data.x,_y:data.y});
});
socket.on('mousemove',function(data){
ev_canvas({type:'mousemove',_x:data.x,_y:data.y});
});
socket.on('mouseup',function(data){
ev_canvas({type:'mouseup',_x:data.x,_y:data.y});
});
// The event handler for any changes made to the tool selector.
function ev_tool_change (ev) {
if (tools[this.value]) {
tool = new tools[this.value]();
socket.emit('tool',this.value);
}
}
socket.emit('tool',tool_default);
socket.on('tool',function(stool){
tool = new tools[stool]();
});
// This function draws the #imageTemp canvas on top of #imageView, after which
// #imageTemp is cleared. This function is called each time when the user
// completes a drawing operation.
function img_update () {
contexto.drawImage(canvas, 0, 0);
context.clearRect(0, 0, canvas.width, canvas.height);
}
// This object holds the implementation of each drawing tool.
var tools = {};
// The drawing pencil.
tools.pencil = function () {
var tool = this;
this.started = false;
// This is called when you start holding down the mouse button.
// This starts the pencil drawing.
this.mousedown = function (ev) {
context.beginPath();
context.moveTo(ev._x, ev._y);
tool.started = true;
};
// This function is called every time you move the mouse. Obviously, it only
// draws if the tool.started state is set to true (when you are holding down
// the mouse button).
this.mousemove = function (ev) {
if (tool.started) {
context.lineTo(ev._x, ev._y);
context.stroke();
}
};
// This is called when you release the mouse button.
this.mouseup = function (ev) {
if (tool.started) {
tool.mousemove(ev);
tool.started = false;
img_update();
}
};
};
// The rectangle tool.
tools.rect = function () {
var tool = this;
this.started = false;
this.mousedown = function (ev) {
tool.started = true;
tool.x0 = ev._x;
tool.y0 = ev._y;
};
this.mousemove = function (ev) {
if (!tool.started) {
return;
}
var x = Math.min(ev._x, tool.x0),
y = Math.min(ev._y, tool.y0),
w = Math.abs(ev._x - tool.x0),
h = Math.abs(ev._y - tool.y0);
context.clearRect(0, 0, canvas.width, canvas.height);
if (!w || !h) {
return;
}
context.strokeRect(x, y, w, h);
};
this.mouseup = function (ev) {
if (tool.started) {
tool.mousemove(ev);
tool.started = false;
img_update();
}
};
};
// The line tool.
tools.line = function () {
var tool = this;
this.started = false;
this.mousedown = function (ev) {
tool.started = true;
tool.x0 = ev._x;
tool.y0 = ev._y;
};
this.mousemove = function (ev) {
if (!tool.started) {
return;
}
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.moveTo(tool.x0, tool.y0);
context.lineTo(ev._x, ev._y);
context.stroke();
context.closePath();
};
this.mouseup = function (ev) {
if (tool.started) {
tool.mousemove(ev);
tool.started = false;
img_update();
}
};
};
init();
});
Any help will be appreciated.
It sounds to me like you want to be using Rooms
You can add users to rooms as they connect just within io.sockets.on('connection')
For example:
io.sockets.on('connection', function (socket) {
socket.join('room');
socket.broadcast.to('room').send("I'm in this room now");
});
You can then use this to broadcast new drawings within just the room of where it originated.