Как исправить событие мыши после изменения оси в левом нижнем углу холста - PullRequest
1 голос
/ 26 сентября 2019

Я изменил ось на холсте html, выполнив

context.translate(0, canvas.height);
context.scale(1,-1);

, чтобы холст перевернулся, и теперь проблема в том, что события мыши не совпадают, когда я хочу нарисовать прямоугольник.например, когда я помещаю мышь, чтобы нарисовать в нижней части холста, прямоугольник появится сверху

Может кто-нибудь, пожалуйста, помогите мне.Пожалуйста, дайте мне некоторые рекомендации или ссылки

, и я использую эту ссылку для моей справки

Установите начало холста в нижнем левом углу

и здеськод фрагмента:

   var ColorCanvas = document.getElementById('ColorCanvas');
        var ctx1 = ColorCanvas.getContext('2d');
        var TransCanvas = document.getElementById('TransCanvas');
        var ctx2 = TransCanvas.getContext('2d');
    
        var rect = {},
            drag = false;


        var bg = new Image();
        bg.src = "Jellyfish.jpg";

        bg.onload = function () {
            ctx1.drawImage(bg, 0, 0);
        }

        var annotation = {
            x: 0,
            y: 0,
            w: 0,
            h: 0,
            a: this.x,
            printCoordinates: function () {
                console.log(`X: ${this.x}px, Y: ${this.y}px, Width: ${this.w}px, Height: ${this.h}px`);   
            }     
        };


        //the array of all rectangles
        var boundingBoxes = [];
        // the actual rectangle, the one that is being drawn
        var o = {};
        
        // a variable to store the mouse position
        var m = {},
            // a variable to store the point where you begin to draw the rectangle
            start = {};
        // a boolean
        var isDrawing = false;

        ctx2.translate(0, TransCanvas.height);
        ctx2.scale(1, -1);

        function handleMouseDown(e) {
            start = oMousePos(TransCanvas, e);
            isDrawing = true;
        }
    
        function handleMouseMove(e) {
            if (isDrawing) {
                m = oMousePos(TransCanvas, e);
                draw();  
            }
        }

        function handleMouseUp(e) {
            isDrawing = false;
            if (boundingBoxes.length < 2) {
                var box = Object.create(annotation);
                box.x = o.x;
                box.y = o.y;
                box.w = o.w;
                box.h = o.h;
                boundingBoxes.push(box);
                draw();
                box.printCoordinates();
            }
        }

        function draw() {
            if (boundingBoxes.length <= 2) {
                o.x = start.x;  // start position of x
                o.y = start.y;  // start position of y
                o.w = m.x - start.x;  // width
                o.h = m.y - start.y;  // height
         
                ctx2.clearRect(0, 0, TransCanvas.width, TransCanvas.height);
                // draw all the rectangles saved in the rectsRy
                boundingBoxes.map(r => { drawRect(r) })
                // draw the actual rectangle
                ctx2.fillRect(x, TransCanvas.height - y, size, size);
                drawRect(o);
            }
        }

        TransCanvas.addEventListener("mousedown", handleMouseDown);
        TransCanvas.addEventListener("mousemove", handleMouseMove);
        TransCanvas.addEventListener("mouseup", handleMouseUp);


        function drawRect(o) {
          
            ctx2.beginPath(o);
            ctx2.strokeStyle = "black";
            ctx2.lineWidth = 1;
            ctx2.rect(o.x, o.y, o.w, o.h);
            ctx2.stroke();
        }

        // Function to detect the mouse position
        function oMousePos(TransCanvas, evt) {
            var ClientRect = TransCanvas.getBoundingClientRect();
            return {
                x: Math.round(evt.clientX - ClientRect.left),
                y: Math.round(evt.clientY - ClientRect.top)
            }
        }
   #TransCanvas {
            position: absolute;
            background-color: rgba(255,255,255,0.1);
            left: 0;
            top: 0;
        }

        #ColorCanvas {
            position: absolute;
            left: 0;
            top: 0;
        }
        #down {
            position: absolute;
            right: 0px;
        }

        body {
            background-color: ivory;
        }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="main-container">
        <canvas id="ColorCanvas" width="700" height="900" style="border:1px solid #000000"></canvas>
        <canvas id="TransCanvas" width="700" height="800"></canvas>
    </div>

1 Ответ

0 голосов
/ 26 сентября 2019

вместо использования e.clientY используйте TransCanvas.height - e.clientY

 // Function to detect the mouse position
    function oMousePos(TransCanvas, evt) {
        var ClientRect = TransCanvas.getBoundingClientRect();
        return {
            x: Math.round(evt.clientX - ClientRect.left),
            y: canvas.height-Math.round(evt.clientY - ClientRect.top)
        }
    }

var ColorCanvas = document.getElementById('ColorCanvas');
        var ctx1 = ColorCanvas.getContext('2d');
        var TransCanvas = document.getElementById('TransCanvas');
        var ctx2 = TransCanvas.getContext('2d');
    
        var rect = {},
            drag = false;


        var bg = new Image();
        bg.src = "Jellyfish.jpg";

        bg.onload = function () {
            ctx1.drawImage(bg, 0, 0);
        }

        var annotation = {
            x: 0,
            y: 0,
            w: 0,
            h: 0,
            a: this.x,
            printCoordinates: function () {
                console.log(`X: ${this.x}px, Y: ${this.y}px, Width: ${this.w}px, Height: ${this.h}px`);   
            }     
        };


        //the array of all rectangles
        var boundingBoxes = [];
        // the actual rectangle, the one that is being drawn
        var o = {};
        
        // a variable to store the mouse position
        var m = {},
            // a variable to store the point where you begin to draw the rectangle
            start = {};
        // a boolean
        var isDrawing = false;

        ctx2.translate(0, TransCanvas.height);
        ctx2.scale(1, -1);

        function handleMouseDown(e) {
            start = oMousePos(TransCanvas, e);
            isDrawing = true;
        }
    
        function handleMouseMove(e) {
            if (isDrawing) {
                m = oMousePos(TransCanvas, e);
                draw();  
            }
        }

        function handleMouseUp(e) {
            isDrawing = false;
            if (boundingBoxes.length < 2) {
                var box = Object.create(annotation);
                box.x = o.x;
                box.y = o.y;
                box.w = o.w;
                box.h = o.h;
                boundingBoxes.push(box);
                draw();
                box.printCoordinates();
            }
        }

        function draw() {
            if (boundingBoxes.length <= 2) {
                o.x = start.x;  // start position of x
                o.y = start.y;  // start position of y
                o.w = m.x - start.x;  // width
                o.h = m.y - start.y;  // height
         
                ctx2.clearRect(0, 0, TransCanvas.width, TransCanvas.height);
                // draw all the rectangles saved in the rectsRy
                boundingBoxes.map(r => { drawRect(r) })
                // draw the actual rectangle
                ctx2.fillRect(x, TransCanvas.height - y, size, size);
                drawRect(o);
            }
        }

        TransCanvas.addEventListener("mousedown", handleMouseDown);
        TransCanvas.addEventListener("mousemove", handleMouseMove);
        TransCanvas.addEventListener("mouseup", handleMouseUp);


        function drawRect(o) {
          
            ctx2.beginPath(o);
            ctx2.strokeStyle = "black";
            ctx2.lineWidth = 1;
            ctx2.rect(o.x, o.y, o.w, o.h);
            ctx2.stroke();
        }

        // Function to detect the mouse position
        function oMousePos(TransCanvas, evt) {
            var ClientRect = TransCanvas.getBoundingClientRect();
            return {
                x: Math.round(evt.clientX - ClientRect.left),
                y: TransCanvas.height-Math.round(evt.clientY - ClientRect.top)
            }
        }
#TransCanvas {
            position: absolute;
            background-color: rgba(255,255,255,0.1);
            left: 0;
            top: 0;
        }

        #ColorCanvas {
            position: absolute;
            left: 0;
            top: 0;
        }
        #down {
            position: absolute;
            right: 0px;
        }

        body {
            background-color: ivory;
        }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="main-container">
        <canvas id="ColorCanvas" width="700" height="900" style="border:1px solid #000000"></canvas>
        <canvas id="TransCanvas" width="700" height="800"></canvas>
    </div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...