【发布时间】:2023-03-06 22:48:02
【问题描述】:
我正在使用 Kinetic.js 库在 JavaScript 中构建一个绘图板应用程序。我在为手绘图实现的代码中遇到了性能问题。基本上,我创建了一个与舞台大小相同的不可见矩形,然后将事件处理程序附加到它以确定绘制线的放置位置。每次按住鼠标左键移动鼠标时,我都会将鼠标坐标添加到一个数组中,并使用该数组中的点来映射我的线。鼠标移动和实际渲染的线条之间大约有一秒钟的延迟。我不确定这种延迟是否是由我自己的代码中的错误或 Kinetic 库中的限制引起的。代码如下:
Whiteboard.prototype.initializeDrawings = function() {
// Create an invisible shape that will act as an event listener
var background = new Kinetic.Rect({
x: 0,
y: 0,
width: this.stage.getWidth(),
height: this.stage.getHeight(),
});
this.mouseDrag = false;
// Attach handlers
background.on('mousedown touchstart', function(e) {
this.mouseDrag = true;
this.currentLine = [];
});
// Save a copy of whiteboard instance
var wb = this;
background.on('mousemove touchmove', function(e) {
if(this.mouseDrag === true) {
this.currentLine.push([e.clientX, e.clientY]);
wb.userDrawings.clear();
wb.userDrawings.add(new Kinetic.Line({
points: this.currentLine,
stroke: 'red',
strokeWidth: 4,
lineCap: 'round',
lineJoin: 'round'
}));
wb.stage.add(wb.userDrawings);
}
});
background.on('mouseup touchstop', function(e) {
this.mouseDrag = false;
});
this.stage.add(new Kinetic.Layer().add(background));
};
总的来说,代码可以工作,但是由于这个应用程序的要求,我需要显着减少移动鼠标和渲染路径之间的延迟。
【问题讨论】:
标签: javascript canvas kineticjs