canvas:以矩形的中心点为缩放基点缩放矩形

512 阅读1分钟

话不多说,直接上代码

<!DOCTYPE html>
<html>
    <head>
            <meta charset="utf-8">
            <title>以矩形的中心点为缩放基点缩放矩形</title>
            <style type="text/css">
                    body {
                            margin: 0;
                            padding: 0;
                            width: 1000px
                    }

                    canvas {
                            border: dashed 10px #ccc
                    }
            </style>
    </head>
    <body>
        <canvas id="canvas" width="900" height="900"></canvas>
    </body>
    <script>
        let context = document.getElementById('canvas').getContext('2d');

        const width = 20;//矩形宽度
        const height = 10;//矩形高度
        const offset = 5;//矩形左上角点(5,5)
        const scale = 3;//缩放比例

        context.translate(300,300);
        context.strokeRect(offset,offset,width,height);

        context.translate(-(scale-1)*offset-(scale-1)*width/2,-(scale-1)*offset-(scale-1)*height/2);
        context.scale(scale,scale);
        context.strokeRect(offset,offset,width,height);

        context.translate(-(scale-1)*offset-(scale-1)*width/2,-(scale-1)*offset-(scale-1)*height/2);
        context.scale(scale,scale);
        context.strokeRect(offset,offset,width,height);

        context.translate(-(scale-1)*offset-(scale-1)*width/2,-(scale-1)*offset-(scale-1)*height/2);
        context.scale(scale,scale);
        context.strokeRect(offset,offset,width,height);
    </script>

</html>