使用NodeJS和Socket.io,我正在制作一个快速的画布应用程序,可以在屏幕上移动一个形状。此数据将显示在所有客户端上。每个正方形都有时间戳以确定绘制顺序。 以下是client.html。它说我“无法设置未定义的属性lastUpdate”。怎么被认为是未定义的?我尝试在顶部多次定义它。怎么了?
<!DOCTYPE html>
<html lang="en">
<head>
<script src="/socket.io/socket.io.js"></script>
<script>
"use strict";
var canvas;
var ctx;
var socket;
//var lastUpdate = new Date().getTime();
/*var square = {
lastUpdate: new Date().getTime(),
x: 0,
y: 0,
height: 100,
width: 100
};*/
//
//var person = {name: 'user' + (Math.floor((Math.random() * 1000)) + 1)};
//var user = 'user' + (Math.floor((Math.random() * 1000)) + 1);
//var user = Object.keys(something about name);
//var user = Object.keys(user);
//function person(name) {
//this.name = name;
//}
//var user = Object.keys(person);
//lets try using a prototype
/*function user(lastUpdate, x, y, width, height) {
this.lastUpdate = lastUpdate;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}*/
var name = {lastUpdate: new Date().getTime(), x: 0, y: 0, width: 100, height: 100};
var user = Object.keys(name);
var draws = {};
function updatePosition() {
var message = {
xUpdate: 10,
yUpdate: 5
}
socket.emit('movementUpdate', message);
}
/*function redraw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(square.x, square.y, square.width, square.height);
}*/
//
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
var keys = Object.keys(draws);
for(var i = 0; i < keys.length; i++)
{
var drawCall = draws[keys[i]];
//order to draw
//gets drawcalls instead of var square
ctx.fillRect(drawCall.x, drawCall.y, drawCall.width, drawCall.height);
}
}
//
function setup() {
var time = new Date().getTime();
//console.log(time);
var x = Math.floor(Math.random()*(300-10) + 10); //random x position
var x = Math.floor(Math.random()*(300-10) + 10); //random y position
draws[user] = {lastUpdate: time, x: x, y: y, width: 100, height: 100};
}
/*function update(data) {
square = data;
redraw();
}*/
//
function handleMessage(data) {
if(!draws[data.name])
{
draws[data.name] = data.coords;
}
else if(data.coords.lastUpdate > draws[data.name].lastUpdate)
{
draws[data.name] = data.coords;
}
draw(); //redraw after updates
}
function init() {
canvas = document.querySelector("#canvas");
ctx = canvas.getContext("2d");
socket = io.connect();
socket.on('connect', function () {
//setInterval(updatePosition, 1000);
setInterval(function()
{
var time = new Date().getTime();
//console.log(time);
console.log(draws);
**draws[user].lastUpdate = time; //lastUpdate is UNDEFINED**
draws[user].x += 5;
socket.emit('draw', {name: user, coords: draws[user]});
draw();
}, 3000);
});
socket.on('updatedDraw', handleMessage);
//socket.on('updatedMovement', updatePosition); //UNDEFINED, used to be 'update'. Could it be 'handleMessage'?
}
window.onload = init;
</script>
</head>
<body>
<canvas id="canvas" height="500" width="500">Please use an HTML 5 browser</canvas>
</body>
</html>