Canvas平移和缩放模型

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="utf-8">

    <title>图形缩放平移</title>

    <script type="text/javascript" src="./js/jquery-1.11.1.min.js"></script>

</head>

<body>

    <canvas id="myCanvas" width="1000" height="800"></canvas>

</body>

<script type="text/javascript">

    class model {

        constructor(canvasid) {

            // 获取Canvas元素

            this.canvas = document.getElementById(canvasid);

            this.ctx = this.canvas.getContext('2d');

            this.mx = 0;

            this.my = 0;

            //平移参数:

            this.cx = 0;

            this.cy = 0;

            //缩放参数:

            this.sx = 1;

            this.sy = 1;

            this.scale = 1.2;

            // 监听鼠标点击事件

            this.canvas.addEventListener('mousedown', (event) => {

                // 获取鼠标点击位置坐标

                var mouseX = event.offsetX;

                var mouseY = event.offsetY;

                // 计算平移的偏移量

                this.cx = mouseX;

                this.cy = mouseY;

                this.paint();

            });

            // 监听鼠标点击事件

            this.canvas.addEventListener('mousemove', (event) => {

                let mat = this.ctx.getTransform();

                // 计算平移的偏移量

                this.cx = event.offsetX;

                this.cy = event.offsetY;

                this.paint();

            });

            // 监听鼠标滚轮事件

            this.canvas.addEventListener('mousewheel', (event) => {

                // 阻止默认的滚轮事件

                event.preventDefault();

                // 进行缩放操作

                let scale = event.wheelDelta > 0 ? this.scale : 1 / this.scale;

                this.sx *= scale;

                this.sy *= scale;

                this.paint();

            });

        }

        paint() {

            //清空背景:

            this.ctx.save();

            this.ctx.resetTransform();

            this.ctx.fillStyle = 'blue';

            this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);

            this.ctx.restore();

            // 绘制示例图形

            this.ctx.save();

            this.ctx.translate(this.cx, this.cy);

            this.ctx.scale(this.sx, this.sy);

            this.ctx.fillStyle = 'red';

            this.ctx.fillRect(-50, -50, 100, 100);

            this.ctx.restore();

        }

    }

    $(document).ready(function() {

        new model("myCanvas");

    });

</script>

</html>

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值