首页 > 解决方案 > 画与画之间的差距边界(使用 Paper.js)

问题描述

我有以下 JavaScript 代码,它<canvas>使用 Paper.js 填充圆圈:

$(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();
});

这应该<canvas>从左到右和从上到下填充,<canvas>边界上没有间隙。但是,我得到的图像在右侧和底部有一点间隙:

我生成的画布

它很微妙,但将其与左边界和上边界进行比较,差异就会变得明显。

为什么会有这个差距?我怎样才能删除它?

标签: javascriptpaperjs

解决方案


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

这是小提琴演示它。

<!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>

推荐阅读