从Paperscript到Javascript

时间:2018-02-26 10:23:38

标签: javascript animation libraries

我试图将Paper.js中的一个库示例(http://paperjs.org/examples/smoothing/)从PaperScript转换为Javascript。在文档之后,我有

  • 使范围全球化

  • 安装了事件处理程序onFrame和onResize

  • 创建了一个工具并安装了事件处理程序onMouseMove和onMouseDown

但画布没有显示。我只看到几条小蓝线:AFAIK问题出在view.onFrame()函数中,因为至少我可以看到它的形状,但不能与它交互。 JS控制台没有显示任何错误。缺少什么?

    // Make the paper scope global, by injecting it into window
    paper.install(window);
    window.onload = function () {

        // Setup directly from canvas id:
        paper.setup('myCanvas');

        // Create tool
        tool = new Tool();

        var width, height, center;
        var points = 10;
        var smooth = true;
        var path = new Path();
        var mousePos = view.center / 2;
        var pathHeight = mousePos.y;
        path.fillColor = 'black';
        initializePath();

        function initializePath() {
            center = view.center;
            width = view.size.width;
            height = view.size.height / 2;
            path.segments = [];
            path.add(view.bounds.bottomLeft);
            for (var i = 1; i < points; i++) {
                var point = new Point(width / points * i, center.y);
                path.add(point);
            }
            path.add(view.bounds.bottomRight);
            path.fullySelected = true;
        }

        view.onFrame = function (event) {
            pathHeight += (center.y - mousePos.y - pathHeight) / 10;
            for (var i = 1; i < points; i++) {
                var sinSeed = event.count + (i + i % 10) * 100;
                var sinHeight = Math.sin(sinSeed / 200) * pathHeight;
                var yPos = Math.sin(sinSeed / 100) * sinHeight + height;
                path.segments[i].point.y = yPos;
            }
            if (smooth)
                path.smooth({ type: 'continuous' });
        }

        tool.onMouseMove = function (event) {
            mousePos = event.point;
        }

        tool.onMouseDown = function (event) {
            smooth = !smooth;
            if (!smooth) {
                // If smooth has been turned off, we need to reset
                // the handles of the path:
                for (var i = 0, l = path.segments.length; i < l; i++) {
                    var segment = path.segments[i];
                    segment.handleIn = segment.handleOut = null;
                }
            }
        }

        // Reposition the path whenever the window is resized:
        view.onResize = function (event) {
            initializePath();
        }


    }

尝试:https://jsfiddle.net/1rtkbp9s/

1 个答案:

答案 0 :(得分:1)

找到解决方案(感谢Paper.js Google Group的StefanKrüger):

var mousePos = view.center / 2;

应该是:

var mousePos = view.center.divide(2);

事实是应该使用Math函数而不是Point和Size对象的运算符......我没有意识到view.center是一个Point对象:http://paperjs.org/reference/view/#center