PaperJS canvas 绘图区域仅在左上角,除非采取外部操作

PaperJS canvas drawing area only in top left corner unless external action taken

我正在尝试创建一个交互式 svg 工具,我希望它最终能够使用 PaperJS 'spot refine' SVG。

完成基础工作进展顺利,但是当我加载我的页面时(在本地打开 html 文件并链接 paperscript-full.js)我可以让鼠标跟随光标,但只能在canvas 左上角的小方块。只要我使用检查工具,我现在就可以自由地使用飞来飞去(我认为是基于边界)——整个 canvas 区域。

这是一个 fiddle,它实际上并没有演示问题,但包含我所有的源代码。我这样做是因为我觉得在这里缩进我的所有代码会花费太长时间:fiddle

此外,它与问题没有严格的联系,但如果有人能告诉我为什么我的 canvas 每次调整大小时宽度都会增加,那将不胜感激

您遇到的有关仅在左上角捕获鼠标事件的问题是由于您在设置 Paper.js 后以编程方式调整 canvas 的大小。
因为你使用的是PaperScript,所以当你的code是运行的时候,Paper.js已经设置好了。至少有两种方法可以解决这个问题:

  • 使用JavaScript代替PaperScript并首先设置canvas大小,然后使用paper.setup()方法手动将Paper.js绑定到canvas .
  • 用CSS控制canvas大小(我在下面的解决方案中选择这种方式)。

关于问题的第二部分,当您调整 window 大小时,您的 canvas 会增长,因为 canvas resize 属性隐式设置为 true你的代码。
引用自 documentation:

resize="true": Makes the canvas object as high and wide as the Browser window and resizes it whenever the user resizes the window. When the window is resized, the size of your global.view is also automatically adjusted.

可以对您的代码进行其他改进,我直接将它们包含在以下示例中:

body,
html {
  width: 100%;
  height: 100%;
  margin: 0;
}


/* set canvas size and position with CSS */

main {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

canvas {
  width: 90vw;
  height: 90vh;
  border: 1px solid;
}

#opts {
  position: absolute;
  right: 10vw;
  bottom: 10vh;
}
<!-- dependencies -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.11.5/paper-full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!-- slider -->
<div id="opts">
  <input id="tool" type="range" name="tool" min="1" max="10" value="1" step="1" />
</div>

<!-- wrap canvas for easier vertical alignment -->
<main>
  <canvas id="canvas" resize></canvas>
</main>

<!-- paper.js code -->
<script type="text/paperscript" canvas="canvas">

    // image should be drawn using paper Raster
    var raster = new Raster({
        source: 'https://picjumbo.com/wp-content/uploads/vineyards-on-italian-coast-free-photo-DSC04256-1080x720.jpg',
        onLoad: function() {
            // position image at view center
            this.fitBounds(view.bounds.scale(0.5));
        }
    });

    // create circle
    var path = new Path.Circle({
        // here you can directly use paper view object
        center: view.center,
        radius: 10,
        // style can directly be set in constructor options
        strokeColor: 'red',
        strokeWidth: 3,
        // disable matrix application for easier scale control
        applyMatrix: false,
        // make stroke width independant from scale
        strokeScaling: false
    });

    // in paperscript context you can directly use named onMouseMove function
    function onMouseMove(event) {
        path.position = event.point;
    }

    // adapt path scale to slider value
    $('#tool').change(function(event) {
        path.scaling = this.value;
    });
</script>