如何在 HTML5 中调整画布的绘图大小?

发布于 2024-12-04 05:52:11 字数 761 浏览 2 评论 0原文

我想将画布的尺寸调整为比实际尺寸更小的尺寸。这是我的代码:

             var modelPane = document.getElementById('model_pane');


        //create canvasclass="modelview"
        var canvas_ = document.createElement('canvas');
        canvas_.setAttribute('width', 1160);
        canvas_.setAttribute('height', 500);
        canvas_.setAttribute('id', 'canvas');
        canvas_.setAttribute('class', 'modelview');
        var ctx_ = canvas_.getContext('2d');

        //draw
        for (i=0;i<nodes.length;i++)
                            {
            ctx_.strokeRect(nodes[i].x,  nodes[i].y, nodes[i].width, nodes[i].height);


    }

        //scale
        ctx_.scale(0.3,0.3);
    modelPane.appendChild(canvas_);

但这不起作用。有人知道为什么吗?画布不会调整为新尺寸。

I would like to resize the canvas to a smaller dimension than what it is. Here is my code:

             var modelPane = document.getElementById('model_pane');


        //create canvasclass="modelview"
        var canvas_ = document.createElement('canvas');
        canvas_.setAttribute('width', 1160);
        canvas_.setAttribute('height', 500);
        canvas_.setAttribute('id', 'canvas');
        canvas_.setAttribute('class', 'modelview');
        var ctx_ = canvas_.getContext('2d');

        //draw
        for (i=0;i<nodes.length;i++)
                            {
            ctx_.strokeRect(nodes[i].x,  nodes[i].y, nodes[i].width, nodes[i].height);


    }

        //scale
        ctx_.scale(0.3,0.3);
    modelPane.appendChild(canvas_);

Yet this doesn't work. Anyone know why? The canvas doesn't resize to the new dimensions.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

乖不如嘢 2024-12-11 05:52:11

您需要首先调用缩放:

var ctx_ = canvas_.getContext('2d');
ctx_.scale(0.3,0.3);
//draw
for (i=0;i<nodes.length;i++)
    ctx_.strokeRect(nodes[i].x,  nodes[i].y, nodes[i].width, nodes[i].height);
}

想一想,就像您需要缩小画布一样。然后在较小的画布上绘制。
示例

You need to call scale first:

var ctx_ = canvas_.getContext('2d');
ctx_.scale(0.3,0.3);
//draw
for (i=0;i<nodes.length;i++)
    ctx_.strokeRect(nodes[i].x,  nodes[i].y, nodes[i].width, nodes[i].height);
}

Think about it, like you need to scale you canvas down. Then draw on the smaller canvas.
Example

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文