【问题标题】:Kinetic.js rendering lines slowly when used in freehand drawingKinetic.js 在手绘中使用时渲染线条缓慢
【发布时间】: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


    【解决方案1】:

    您不希望每次鼠标移动都创建一个新的 Kinetic.Line...

    为了获得更好的性能:

    不是在每次 mousemove 时都创建一个新的 Kinetic.Line,而是在 mousedown 处理程序中创建一个新 Line,并在 mousemove 中向该现有行添加点。

    // a var which will eventually hold a Kinetic.Line (in your class or in global scope)
    
    var myExistingLine;
    
    // in mousedown
    
    myExistingLine=new Kinetic.Line({ ...
    
    // in mousemove
    
    currentLine.push([mouseX,mouseY]);
    
    myExistingLine.setPoints(currentLine);
    
    myExistingLine.draw();  // or layer.drawScene();
    

    为了获得最佳性能:

    创建一个 Kinetic.Shape,它使您可以访问包装的画布上下文。让用户在该上下文上绘制他们的折线。在用户创建了他们的折线后,您可以将这些点放在新的 Kinetic.Line 中以获得“托管”折线的好处 - 并删除 Kinetic.Shape。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-03
      • 1970-01-01
      • 2020-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-14
      • 1970-01-01
      相关资源
      最近更新 更多