【问题标题】:Gap between drawing and <canvas> boundary (using Paper.js)绘图和 <canvas> 边界之间的间隙(使用 Paper.js)
【发布时间】:2021-06-30 14:29:48
【问题描述】:

我有以下 JavaScript 代码,它使用 Paper.js 用圆圈填充 &lt;canvas&gt;

$(document).ready(() => {
    'use strict';

    paper.install(window);
    paper.setup(document.getElementById('mainCanvas'));

    const CANVAS_WIDTH = 400;
    const CANVAS_HEIGHT = 400;

    const RADIUS = 10;
    const FILL_COLOR = 'green';

    for (let x = RADIUS; x <= CANVAS_WIDTH - RADIUS; x += 2 * RADIUS) {
        for (let y = RADIUS; y <= CANVAS_HEIGHT - RADIUS; y += 2 * RADIUS) {
            let c = Shape.Circle(x, y, RADIUS);
            c.fillColor = FILL_COLOR;
        }
    }

    paper.view.draw();
});

这应该从左到右和从上到下填充&lt;canvas&gt;&lt;canvas&gt; 边界上没有间隙。但是,我得到的这张图片在右侧和底部有一点缝隙:

很微妙,但是对比一下左上边界,区别就很明显了。

为什么会有这个差距?如何删除它?

【问题讨论】:

    标签: javascript paperjs


    【解决方案1】:

    这个间隙是边框应用到画布的结果。 您可以通过将画布的 CSS box-sizing 属性设置为 border-box 来轻松摆脱它。

    这里是fiddle 演示它。

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Debug Paper.js</title>
        <script src="https://unpkg.com/acorn"></script>
        <script src="https://unpkg.com/paper"></script>
        <style>
            canvas {
                width      : 400px;
                height     : 400px;
                border     : 1px solid;
                box-sizing : border-box;
            }
        </style>
    </head>
    <body>
    <canvas id="canvas"></canvas>
    <script>
        paper.setup('canvas');
    
        const CANVAS_WIDTH = 400;
        const CANVAS_HEIGHT = 400;
    
        const RADIUS = 10;
        const FILL_COLOR = 'green';
    
        for (let x = RADIUS; x <= CANVAS_WIDTH - RADIUS; x += 2 * RADIUS) {
            for (let y = RADIUS; y <= CANVAS_HEIGHT - RADIUS; y += 2 * RADIUS) {
                let c = paper.Shape.Circle(x, y, RADIUS);
                c.fillColor = FILL_COLOR;
            }
        }
    
        console.log('canvas width = ', paper.view.bounds.width);
    </script>
    </body>
    </html>
    

    【讨论】: