GoJS 浏览器窗口缩放后自动居中对齐
GoJS About 3,281 words需求
因为GoJS开启了可以拖动和缩放后,在窗口大小充足的情况下,默认不会进行自动居中对齐的,需求是在浏览器窗口缩小和最大化时,GoJS中的元素能居中对齐。
contentAlignment
Diagram中可以设置contentAlignment内容对齐,但这个设置就导致元素将无法拖动,每次拖动后都将被GoJS自动居中对齐。
而initialContentAlignment则是在初始化时居中对齐,对于缩放后无法起到再次居中的效果
alignDocument
alignDocument方法可以手动设置与文档对齐方式,但如果只使用这个API缩放几次后还是会出现无法对齐的现象。
解决方法
在onresize事件中,先将contentAlignment设置为Center,再调用alignDocument方法让元素在document和viewport中都居中,然后再将contentAlignment改为Default。
let that = this;
window.onresize = function () {
    console.log("resize");
    that.diagram.contentAlignment = go.Spot.Center;
    that.diagram.alignDocument(go.Spot.Center, go.Spot.Center);
    that.diagram.contentAlignment = go.Spot.Default;
}效果
完整代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gojs/2.1.38/go.js" crossorigin="anonymous"></script>
    <style>
        #myDiagramDiv canvas {
            outline: none;
        }
    </style>
</head>
<body>
<div id="myDiagramDiv" style="height:300px;background: #E4E7EB"></div>
<script>
    var $ = go.GraphObject.make;
    var diagram = $(go.Diagram, "myDiagramDiv",
        {
            allowMove: true,
            allowSelect: true,
            hasVerticalScrollbar: false,
            hasHorizontalScrollbar: false,
        }
    );
    diagram.add(
        $(go.Node, "Vertical",
            $(go.Panel, "Auto",
                $(go.Shape, "Rectangle",
                    {
                        stroke: "#00FFFF",
                        strokeWidth: 2,
                        fill: "#F0F8FF",
                        desiredSize: new go.Size(120, 60),
                    },
                ),
                $(go.TextBlock,
                    {margin: 3, stroke: "green", text: "程序员技术之旅"},
                ),
                {
                    contextClick: function (e, node) {
                        node.elements.each(function (element) {
                            console.log(element);
                        })
                    },
                }
            ),
        )
    );
    let that = this;
    window.onresize = function () {
        console.log("resize");
        that.diagram.contentAlignment = go.Spot.Center;
        that.diagram.alignDocument(go.Spot.Center, go.Spot.Center);
        that.diagram.contentAlignment = go.Spot.Default;
    }
</script>
</body>
</html>Diagram 文档
                Views: 3,942 · Posted: 2021-11-24
            
            ————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
 
        Loading...