canvas画布操作(平移,缩放,交互缩放)

已被阅读 2138 次 | 文章分类:javascript | 2021-07-02 00:10

canvas 是html的一个特殊标签,利用JavaScript 在网页上绘制图像。 我们可以控制canvas区域的每一像素。并且拥有多种绘制路径、矩形、圆形、字符以及添加图像的方法。

1 canvas 画布平移

画布平移使用的方法是 ctx.translate(x,y);这里我们将画布往x轴正方向和y轴正方向平移一半距离;那么canvas画布的(0,0)位置,自然就在中心位置了

/net/upload/image/20210702/5617e173-bb5a-48db-ac61-75362255b556.jpg

全部代码

                                            
<html xmlns="http://www.w3.org/1999/xhtml">
 
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>canvas 平移</title>
    <style type="text/css">
        html,
        body {
            border: 0;
            margin: 0;
            padding: 0;
            width: 100%;
            height: 100%;
            font-size: 13px;
        }
    </style>
</head>
 
<body>
    <canvas id='canvas'></canvas>
    <script type="text/javascript">
        //初始化canvas
        let canvas = document.getElementById('canvas');
        let ctx = canvas.getContext('2d');
        let width = canvas.width = 500;
        let height = canvas.height = 500;
        ctx.lineWidth = "2";
        ctx.fillStyle = "green";
        ctx.rect(0, 0, width, height);
        ctx.fill();
        ctx.strokeStyle = "red";
        ctx.stroke();
        // 绘制网格
        grid(width, height, 50);
        originText(width, height, ctx);
        function originText(width, height, ctx) {
            ctx.translate(width / 2, height / 2);
            ctx.font = "12px Arial";
            ctx.fillStyle = "white";
            ctx.beginPath();
            ctx.fillStyle = 'white';
            ctx.arc(0, 0, 5, 0, Math.PI * 2, false);
            ctx.fillText("新原点(0,0)", 0, 0);
            ctx.arc(-width / 2, -height / 2, 5, 0, Math.PI * 2, false);
            ctx.fill();
            ctx.fillText("旧原点(0,0)", -width / 2 + 10, -height / 2 + 10);
        }
 
        function grid(width, height, interval) {
            for (let y = 50; y < height; y = y + interval) {
                ctx.beginPath();
                ctx.moveTo(0, y);
                ctx.lineTo(width, y);
                ctx.stroke();
            }
            for (let x = 50; x < width; x = x + interval) {
                ctx.beginPath();
                ctx.moveTo(x, 0);
                ctx.lineTo(x, height);
                ctx.stroke();
            }
        }
    </script>
</body>
 
</html>
                                            
                                        

2 canvas 缩放变换

很简单一个方法; 例如 ctx.scale(2, 2)

/net/upload/image/20210702/034d7774-009d-4042-9dd4-034d7bd7debb.jpg

全部代码

                                            
<html xmlns="http://www.w3.org/1999/xhtml">
 
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>canvas 放缩</title>
    <style type="text/css">
        html,
        body {
            border: 0;
            margin: 0;
            padding: 0;
            width: 100%;
            height: 100%;
            font-size: 13px;
        }
    </style>
</head>
 
<body>
    <canvas id='canvas'></canvas>
    <script type="text/javascript">
        //初始化canvas
        let canvas = document.getElementById('canvas');
        let ctx = canvas.getContext('2d');
        const width = canvas.width = 500;
        const height = canvas.height = 500;
 
        ctx.fillStyle = "green";
        ctx.fillRect(0, 0, 50, 50);
        grid(width, height, 25)
        ctx.globalCompositeOperation = "destination-over";
        ctx.scale(2, 2); //执行该句后;后续绘制每像素单位为之前的2倍
        ctx.fillStyle = 'red'
        ctx.fillRect(50, 50, 50, 50);
 
        function grid(width, height, interval) {
            for (let y = 25; y < height; y = y + interval) {
                ctx.beginPath();
                ctx.moveTo(0, y);
                ctx.lineTo(width, y);
                ctx.stroke();
            }
            for (let x = 25; x < width; x = x + interval) {
                ctx.beginPath();
                ctx.moveTo(x, 0);
                ctx.lineTo(x, height);
                ctx.stroke();
            }
        }
    </script>
</body>
 
</html>
                                            
                                        

3 鼠标滚动缩放,拖动平移

结合鼠标mousewheel,drag等事件,交互拖动和缩放canvas;原理就是鼠标没交互一次,将画布清除,然后重绘;效果和全部代码如下

                                            
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>canvas 鼠标缩放 拖动平移</title>
    <style>
      canvas {
        border: 1px solid #ccc;
      }
    </style>
  </head>
 
  <body>
    <canvas id="canvas" width="500" height="500"></canvas>
    <script type="text/javascript">
      (function() {
        var c = document.getElementById('canvas');
        var ctx = c.getContext('2d');
        var ax,
          ay,
          r = 30,
          num = 1; //绘制图形的参数
        var timeOutEvent = 0; //区分拖拽和点击的参数
        //创建图形
        function createBlock(a, b, r) {
          ctx.beginPath();
          ctx.fillStyle = 'red';
          ctx.arc(a, b, r, 0, Math.PI * 2);
          ctx.fill();
        }
        createBlock(200, 200, 30);
        c.onmousedown = function(ev) {
          var e = ev || event;
          var x = e.clientX;
          var y = e.clientY;
          timeOutEvent = setTimeout('longPress()', 500);
          e.preventDefault();
          drag(x, y, r);
        };
        //缩放
        c.onmousewheel = function(ev) {
          var e = ev || event;
          num += e.wheelDelta / 1200;
          r = 30 * num;
          ctx.clearRect(0, 0, c.width, c.height);
          if (ax == null || ay == null) {
            createBlock(200, 200, r);
          } else {
            if (r > 0) {
              createBlock(ax, ay, r);
            }
          }
        };
        //拖拽函数
        function drag(x, y, r) {
          if (ctx.isPointInPath(x, y)) {
            //路径正确,鼠标移动事件
            c.onmousemove = function(ev) {
              var e = ev || event;
              ax = e.clientX;
              ay = e.clientY;
              clearTimeout(timeOutEvent);
              timeOutEvent = 0;
              //鼠标移动每一帧都清除画布内容,然后重新画圆
              ctx.clearRect(0, 0, c.width, c.height);
              createBlock(ax, ay, r);
            };
            //鼠标移开事件
            c.onmouseup = function() {
              c.onmousemove = null;
              c.onmouseup = null;
              clearTimeout(timeOutEvent);
              if (timeOutEvent != 0) {
                alert('你这是点击,不是拖拽');
              }
            };
          }
        }
       function longPress() {
          timeOutEvent = 0;
        }
      })();
    </script>
  </body>
</html>
                                            
                                        

/net/upload/image/20210702/f22be50c-06ba-485d-84b3-4ad021a7b46b.gif

其他canvas的鼠标交互事件 比如跟随鼠标线性移动 可查看canvas绘制动画球,并通过鼠标交互移动

QQ:3410192267 | 技术支持 微信:popstarqqsmall

Copyright ©2017 xiaobaigis.com . 版权所有 鲁ICP备17027716号