javascript对象出现问题



我想为我的朋友制作一个skribl复制品。为此,我使用javascript和websocket。绘图画布需要共享,所以我将数据发送到服务器,以便在其他画布上重新绘制。为此,我使用了一个函数:

function newDrawing(data){  
context.beginPath();
context.lineTo(data.x, data.y);
context.moveTo(data.x, data.y);
context.stroke();
}
}

我使用保存值

let data={
x: e.clientX-this.offsetLeft,
y: e.clientY-this.offsetTop
}

但我没有得到一条直线。我的理解是context.lineTo(data.x,data.y(;和context.moveTo(data.x,data.y(;开始和结束在同一点,我不知道如何解决这个问题,因为我对这种语言还很陌生。有人能帮我吗?

我认为问题可能来自于传递给函数newDrawing的参数以及如何使用它们例如,现在你似乎这样称呼它:newDrawing({x:10,y:10}(;这意味着你只通过了一个论点所以在术语上,你画了相同的点

您还反转了moveTo和lineTo。

所以你会在最后得到以下代码:

let ctx = can.getContext("2d");
const newDrawing = (data) => {  
ctx.beginPath();
ctx.lineWidth = "5";
ctx.strokeStyle = "green";
ctx.moveTo(data.x, data.y);
ctx.lineTo(data.x2, data.y2);
ctx.stroke();
}

newDrawing({x:10,y:10,x2:100,y2:10});
<canvas id=can height=200 width=300 ></canvas>

但你正在寻找的东西看起来更像这样:

let ctx = can.getContext("2d");
let prev = undefined;
const newDrawing = (data) => {  
ctx.beginPath();
ctx.lineWidth = "5";
ctx.strokeStyle = "green";
ctx.moveTo(data.x, data.y);
ctx.lineTo(data.x2, data.y2);
ctx.stroke();
}

const createAndDraw = ev =>{
if(!prev) prev={x:ev.clientX,y:ev.clientY};
newDrawing({x:prev.x,y:prev.y,x2:ev.clientX,y2:ev.clientY});
prev={x:ev.clientX,y:ev.clientY};
}
can.addEventListener("mousemove", createAndDraw);
<canvas id=can height=200 width=300 ></canvas>

相关内容

最新更新