Paper.js won't resize the canvas correctly

2020-05-20 01:47发布

I'm trying out Paper.js for fun, but it seems I'm already stuck at the very start.

Adding resize="true" to the canvas tag is supposed to make the element as high and wide as the browser window. However, doing that results in some rather strange behavior.

I expected the canvas to adjust itself to the viewport right after loading the page, but it didn't do so, which is why I initially thought it didn't resize at all. What actually happens, though, is even more bizarre: The canvas starts out at its default size of 300x150, and when I resize the viewport, it grows - slowly, but indefinitely.

For the record, I've tried using data-paper-resize="true" or just resize instead, or using Chrome instead of Firefox - all to no avail.

I'm not expecting an answer if this problem is caused by some inexplicably weird setup on my end. I am wondering, however, if the problem is common (or even known to exist at all) and has known causes and solutions.

Here's the code I'm using:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <script type="text/javascript" src="paper-full.min.js"></script>
        <script type="text/paperscript" canvas="myCanvas">

            var path = new Path();
            path.strokeColor = 'black';
            path.moveTo(new Point(120, 120));
            path.lineTo(new Point(500, 500));

        </script>
    </head>
    <body>
        <canvas id="myCanvas" style="border: 1px dotted red;" resize="true"></canvas>
    </body>
</html>

3条回答
Lonely孤独者°
2楼-- · 2020-05-20 02:40

I opened an issue for this on Github and it seems that this is a bug introduced in 0.9.22. @Skalkaz pointed me this question.

Here is the pending issue: https://github.com/paperjs/paper.js/issues/662.

You can also downgrade to 0.9.21 while waiting for a patch.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-05-20 02:42

Add the following CSS to your project:

<style type="text/css">
html,
body {
    margin: 0;
    overflow: hidden;
    height: 100%;
}

/* Scale canvas with resize attribute to full size */
canvas[resize] {
    width: 100%;
    height: 100%;
}
</style>
查看更多
家丑人穷心不美
4楼-- · 2020-05-20 02:48

Another option is - if you are using set proportions (relative to the body) - to override paper's view:

var pageWidth = document.getElementsByTagName("BODY")[0].clientWidth
var pageHeight = document.getElementsByTagName("BODY")[0].clientHeight
view.size.width = pageWidth * myWidthScale
view.size.height = pageHeight * myHeightScale
center = new Point(width / 2, pageHeight / 2)
view.center = center
查看更多
登录 后发表回答