Rectangle vertices coordinates using canvas rect

151 views Asked by At

I'm trying to draw rectangle on canvas in this way:

<canvas id="canvas" height="893" width="1262"></canvas>
<div id="output"></div>


<script>

var canvasSizeX = 1262;
var canvasSizeY = 893;


var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.globalAlpha = 0.5;
//Variables
var canvasx = $(canvas).offset().left;
var canvasy = $(canvas).offset().top;

var canvasybottom = $(canvas).offset().bottom;

var last_mousex = last_mousey = 0;
var mousex = mousey = 0;
var mousedown = false;

// points
var A;
var B;
var C;
var D;

//Mousedown
$(canvas).on('mousedown', function (e) {
    last_mousex = parseInt(e.clientX - canvasx);
    last_mousey = parseInt(e.clientY - canvasy);
    mousedown = true;
});

//Mouseup
$(canvas).on('mouseup', function (e) {
    mousedown = false;
});

//Mousemove
$(canvas).on('mousemove', function (e) {

    mousex = parseInt(e.clientX - canvasx);
    mousey = parseInt(e.clientY - canvasy);

    if (mousedown) {
        ctx.clearRect(0, 0, canvas.width, canvas.height); //clear canvas
        ctx.beginPath();
        var width = mousex - last_mousex;
        var height = mousey - last_mousey;
        ctx.rect(last_mousex, last_mousey, width, height);
        ctx.strokeStyle = 'red';
        ctx.lineWidth = 7;
        ctx.stroke();

        //
        // Here I need the A, B, C and D values
        //
    }
    //Output
    $('#output').html('current: ' + mousex + ', ' + mousey + '<br/>last: ' + last_mousex + ', ' + last_mousey + '<br/>mousedown: ' + mousedown + '<br/>A: ' + A + '<br/>B: ' + B + '<br/>C: ' + C + '<br/>D: ' + D);
});

</script>

When the rect is drawn, I'd like to know the A, B, C and D (vertices) coordinates. On mousemove event actually I can get only the width the mouse X and mouse Y coordinates. Is there a way to do it or I'm missing something?

0

There are 0 answers