【问题标题】:Speeding up my KineticJS drawing canvas on mobile加快我的KineticJS在移动上绘制画布
【发布时间】:2013-08-07 17:38:07
【问题描述】:

我希望将 KineticJS 用作绘图画布,它在桌面浏览器上运行良好,但在移动浏览器上运行缓慢。现在,当鼠标移动并将新点设置为标记线时,我只是在图层上不断调用 draw。

我可以做些什么来优化速度而不失去绘图的平滑度?

var stage;
var input;
var marker;
var points = [];

function initialize() {
    stage = new Kinetic.Stage({
    container: 'container',
        width: $(window).width(),
        height: $(window).height()
    });

    input = new Kinetic.Layer();
    stage.add(input);
    marker = new Kinetic.Line({
        stroke: 'red',
        strokeWidth: 16,
        lineCap: 'round',
        lineJoin: 'round'
    });
    input.add(marker);

    stage.on('mousedown touchstart', handleMouseDown);
    stage.on('mouseup touchend', handleMouseUp);
}

function handleMouseDown() {
    points = [];
    stage.on('mousemove touchmove', handleMouseMove);
}

function handleMouseMove() {
    points.push(stage.getPointerPosition());
    marker.setAttr('points', points);
    input.draw();
}

function handleMouseUp() {
    stage.off('mousemove touchmove');
}

【问题讨论】:

    标签: html5-canvas kineticjs


    【解决方案1】:

    您可以通过将绘图与鼠标移动分离来提高性能。

    因为 mousemove 是经常重复进行的,所以只需在 handleMouseMove 中收集点。

    function handleMouseMove() {
        points.push(stage.getPointerPosition());
    }
    

    然后设置一个定时器循环来批量绘制。

    最好使用 requestAnimationFrame,但对于某些移动设备,您可能必须使用 setTimeout

    这将大大减少所需的昂贵 input.draw 的数量。

        // thank you Paul Irish for this RAF/setTimeout shim
    
        window.requestAnimFrame = (function(callback) {
          return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
          function(callback) {
            window.setTimeout(callback, 1000 / 60);
          };
        })();
    
    // draw the points in a batch when RAF fires 
    
    function batchDraw() {
        marker.setAttr('points', points);
        input.draw();
        requestAnimFrame(batchDraw);
    }
    

    【讨论】:

    • 这是一个不错的选择,但它不会消除直接和“绘图的流畅性”吗?
    • 我听到你的声音,我的朋友,但是……我读到 OP 说“加速……”、“非常缓慢”、“优化速度”。这种编码模式将通过将多个昂贵的抽签分批成 1 个有效抽签来帮助满足对速度的需求。这段代码没有做任何线条平滑,但它确实给了移动 CPU 更多时间来监听鼠标移动。移动 CPU 可以收集更多数据点,从而产生更平滑的结果。我确实有通过点样条来平滑路径的代码,但我的经验表明这些样条计算在移动设备上引入了它们自己的性能问题。
    • 我同意这肯定会节省一些处理能力,因为调用 handleMouseMove 相当费力。我看到的一个问题是我的目标是移动设备,而 Android 存在一些臭名昭著的问题,即 setTimeout 无法在所有设备上以标准方式运行。
    • 我一直在使用 CreateJS,如果我使用这种类似的代码设置,它在移动设备和桌面设备上运行非常流畅。我想知道两者在后端有什么区别?
    • 在底层,KineticJS 在处理阶段 mousemove 事件时检查相交节点。这种命中测试虽然通常很有用,但会导致鼠标移动的处理速度相对较慢。由于您只是在收集拖动点,您可以尝试绕过 Kinetic mousemove 事件处理并改为收听浏览器的本机 mousemove。无论哪种方式,您都将受益于从 mousemove 事件中取消链接绘制。
    猜你喜欢
    • 2013-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-20
    • 2012-11-24
    • 1970-01-01
    • 2013-03-04
    • 2015-12-03
    相关资源
    最近更新 更多