以下是我的data
对象。
data = {
user: loggedInUser,
shape: 4,
width: currentThickness,
color: currentColor,
start_x: canvasX,
start_y: canvasY,
end_x: -1,
end_y: -1,
path_data: []
};
我想将一些数据添加到path_data
。
data.path_data.push({
x: canvasX,
y: canvasY
});
但这似乎没有向path_data
添加任何内容。
如何将对象添加到path_data
?
编辑:此处提供了完整的代码
var canvas;
var ctx;
var canvasWidth = 490;
var canvasHeight = 220;
var currentThickness;
var currentColor;
var data;
var message;
var webSocket;
var loggedInUser = "user";
var mouseDown = false;
window.onload = function() {
$(document).mousedown(function() {
mouseDown = true;
});
$(document).mouseup(function() {
mouseDown = false;
});
canvas = document.getElementById("canvas");
currentColor = $('#selectColor option:selected').val();
currentThickness = parseInt($('#selectThickness option:selected').val());
var canvasX;
var canvasY;
if (canvas) {
ctx = canvas.getContext("2d");
ctx.lineWidth = currentThickness;
$(canvas)
.mousedown(function(e) {
prepareStartPointPath(e);
})
.mousemove(function(e) {
if (mouseDown != false) {
canvasX = e.pageX - canvas.offsetLeft;
canvasY = e.pageY - canvas.offsetTop;
ctx.lineTo(canvasX, canvasY);
ctx.lineWidth = currentThickness;
ctx.strokeStyle = currentColor;
ctx.stroke();
data.path_data.push({
x: canvasX,
y: canvasY
});
}
})
.mouseup(function(e) {
prepareEndPointPath(e);
})
.mouseleave(function(e) {
if (mouseDown) {
prepareEndPointPath(e);
}
})
.mouseenter(function(e) {
if (mouseDown) {
prepareStartPointPath();
}
});
}
$('#selectColor').change(function() {
currentColor = $('#selectColor option:selected').val();
});
$('#selectThickness').change(function() {
currentThickness = parseInt($('#selectThickness option:selected').val());
});
};
function prepareWebSocket() {
console.log("preparing web socket");
webSocket = new WebSocket("ws://192.168.99.70:2012");
webSocket.onopen = function(evt) {
onOpen(evt)
};
webSocket.onclose = function(evt) {
onClose(evt)
};
webSocket.onmessage = function(evt) {
onMessage(evt)
};
webSocket.onerror = function(evt) {
onError(evt)
};
}
function onOpen(evt) {
console.log("Open");
}
function onClose(evt) {
console.log("Close");
}
function onMessage(evt) {
console.log("received: " + evt.data);
re(JSON.parse(evt.data));
}
function onError(evt) {
console.log(evt.data);
}
function prepareStartPointPath(e) {
var canvasX;
var canvasY;
ctx.beginPath();
canvasX = e.pageX - canvas.offsetLeft;
canvasY = e.pageY - canvas.offsetTop;0
data = {
user: loggedInUser,
shape: 4,
width: currentThickness,
color: currentColor,
start_x: canvasX,
start_y: canvasY,
end_x: -1,
end_y: -1,
path_data: []
};
ctx.moveTo(canvasX, canvasY);
ctx.lineWidth = currentThickness;
ctx.strokeStyle = currentColor;
}
function prepareEndPointPath(e) {
var canvasX;
var canvasY;
ctx.closePath();
canvasX = e.pageX - canvas.offsetLeft;
canvasY = e.pageY - canvas.offsetTop;
data.end_x = canvasX;
data.end_y = canvasY;
console.log(JSON.stringify(data));
}
答案 0 :(得分:-2)
你可以这样做: data.path_data = {X: “canvasX”,Y: “canvasY”};