动态调整画布大小后,HTML5画布图形放错了位置

问题描述

我想知道是否有人可以帮助我。我在画布上放置了一个圆并动态调整了画布的大小,但是这样做时我的圆放错了位置。我想知道是否有人可以帮助我解决这个问题。图1在字母'O'的中间显示一个红色圆圈,图2在调整画布大小后不在预期位置显示红色圆圈(仍应在该字母的中间继续'O')。

这是我的html和javascript:

        var points_x = new Array();
        var points_y = new Array();

        var img = document.getElementById("img");
        var original_width = img.naturalWidth;
        var original_height = img.naturalHeight;
        var current_width = original_width; 

        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");

        canvas.width = original_width;
        canvas.height = original_height;

        function saveResizeAndRedisplay(scaleFactor) {
                    
            current_width += scaleFactor;
            img.width = current_width;
            
            // resize the canvas
            canvas.width += scaleFactor;
            canvas.height += scaleFactor;

            for (var i = 0; i < points_x.length; i++) {
                
                //this is where things are going wrong !!!
                points_x[i] += scaleFactor;
                    points_y[i] += scaleFactor;
            }

            redraw_points_after_zoom();
        }

        canvas.addEventListener("mousedown",function(e) {
            getMousePosition(canvas,e);
        });

        function getMousePosition(canvas,event) {

            var rect = canvas.getBoundingClientRect();
            var x = event.clientX - rect.left;
            var y = event.clientY - rect.top;

            points_x.push(x);
            points_y.push(y);

            var radius = 3;
            ctx.beginPath();
            ctx.arc(x,y,radius,2 * Math.PI,false);
            ctx.fillStyle = 'red';
            ctx.fill();
        }

        function redraw_points_after_zoom() {

            var radius = 3;

            for (var i = 0; i < points_x.length; i++) {

                ctx.beginPath();
                    ctx.arc(points_x[i],points_y[i],false);
                    ctx.fillStyle = 'red';
                    ctx.fill();
            }
        }

        $("#resizer").click(function() {
          saveResizeAndRedisplay(50);
        });
        body {
            background-color: ivory;
            padding:10px;
        }
        canvas {
            border:1px solid red;
        }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div style="display: inline-block;">
  
  <button id="resizer">Click to resize the canvas</button>

  <br/>
  <img id="img" src="https://www.miamidade.gov/resources/images/services/adopt-a-tree-logo-01-08-2019.png" alt="" style="z-index: 1;position: absolute;">
  
  <canvas id="canvas" style="z-index: 20;position: relative;"></canvas>

</div>

感谢您的帮助

P.S .:我不想保存,想将画布的内容另存为img并重新加载。

解决方法

每次调整画布大小时,都需要重新绘制布局。因此,您可能需要将draw函数附加到resize事件中。如果您担心性能(由于每次调整大小都导致不必要的渲染),请查看去抖动api。

debounce