Display rectangle on canvas when mouse moves


Ajay Thakur



I want to draw rectangle on canvas. The code below works fine, except when I draw the rectangle, it doesn't show the path when the mouse moves. When I leave the mouse, the rectangle is visible on the canvas.

please help,

thanks

var canvas, ctx, flag = false,
        prevX = 0,
        currX = 0,
        prevY = 0,
        currY = 0,
        currShape = 'rectangle',
        mouseIsDown = 0,
        startX, endX, startY, endY,
        dot_flag = false;

    var x = "white",
        y = 2;
   
    function init() {
        canvas = document.getElementById('can');
        ctx = canvas.getContext("2d");
        var imageObj = new Image(); //Canvas image Obj

        imageObj.onload = function() {
            ctx.drawImage(imageObj, 69, 50);    //Load Image on canvas
        };
        imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg'; //Load Image 

        w = canvas.width;   // Canvas Width
        h = canvas.height;  // Canvas Height
        //Check Shape to be draw
        eventListener();

    }
    function eventListener(){
        if(currShape=='rectangle'){
            canvas.addEventListener("mousedown",function (e) { 
                mouseDown(e);
            }, false);
            canvas.addEventListener("mousemove",function (e){
                mouseXY(e);
            }, false);
            canvas.addEventListener("mouseup", function (e){ 
                mouseUp(e);
            }, false);
        }
    }

function mouseUp(eve) {
    if (mouseIsDown !== 0) {
        mouseIsDown = 0;
        var pos = getMousePos(canvas, eve);
        endX = pos.x;
        endY = pos.y;
        if(currShape=='rectangle')
        {
            drawSquare(); //update on mouse-up
        }
    }
}

function mouseDown(eve) {
    mouseIsDown = 1;
    var pos = getMousePos(canvas, eve);
    startX = endX = pos.x;
    startY = endY = pos.y;
    if(currShape=='rectangle')
    {
        drawSquare(); //update on mouse-up
    }
}

function mouseXY(eve) {
    if (mouseIsDown !== 0) {
        var pos = getMousePos(canvas, eve);
        endX = pos.x;
        endY = pos.y;
        //drawSquare();
    }
}

function drawSquare() {
    // creating a square
    var w = endX - startX;
    var h = endY - startY;
    var offsetX = (w < 0) ? w : 0;
    var offsetY = (h < 0) ? h : 0;
    var width = Math.abs(w);
    var height = Math.abs(h);

               
    ctx.beginPath();
    ctx.globalAlpha=0.7;
    ctx.rect(startX + offsetX, startY + offsetY, width, height);
    ctx.fillStyle = x;
    ctx.fill();
    ctx.lineWidth = y;
    ctx.strokeStyle = x;
    ctx.stroke();
}

function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
        x: evt.clientX - rect.left,
        y: evt.clientY - rect.top
    };
}
.colortool div {
        width: 15px;
        height: 15px;
        float: left;
        margin-left: 2px;
    }
    .clear {
      clear: both;
    }
<!DOCTYPE HTML>
<html>
    <body onload="init()">
     <div class="canvasbody">
     <canvas id="can" width="400" height="400" style="border:1px dotted #eee;"></canvas>
     </div>
    </body>
    </html>

Charlie Baldry

This is your new JavaScript

var canvas, cnvHid, cnvRender, ctx, flag = false,
        prevX = 0,
        currX = 0,
        prevY = 0,
        currY = 0,
        currShape = 'rectangle',
        mouseIsDown = 0,
        startX, endX, startY, endY,
        dot_flag = false;

    var x = "white",
        y = 2;

    function init() {
        canvas = document.getElementById('can');
        cnvHid = document.getElementById( "canHid" );
        cnvRender = document.getElementById( "canRend" );
        ctx = canvas.getContext("2d");
        var imageObj = new Image(); //Canvas image Obj

        imageObj.onload = function() {
            ctx.drawImage(imageObj, 69, 50);    //Load Image on canvas
            renderAllCanvas();
        };
        imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg'; //Load Image 

        w = canvas.width;   // Canvas Width
        h = canvas.height;  // Canvas Height
        //Check Shape to be draw
        eventListener();
    }
    function eventListener(){
        if(currShape=='rectangle'){
            cnvRender.addEventListener("mousedown",function (e) { 
                mouseDown(e);
                renderAllCanvas();
            }, false);
            cnvRender.addEventListener("mousemove",function (e){
                mouseXY(e);
                renderAllCanvas();
            }, false);
            cnvRender.addEventListener("mouseup", function (e){ 
                mouseUp(e);
                renderAllCanvas();
            }, false);
        }
    }
    function mouseUp(eve) {
    if (mouseIsDown !== 0) {
        mouseIsDown = 0;
        var pos = getMousePos(canvas, eve);
        endX = pos.x;
        endY = pos.y;
        if(currShape=='rectangle')
        {
            drawSquare( canvas ); //update on mouse-up
            cnvHid.getContext( "2d" ).clearRect( 0, 0, cnvHid.width, cnvHid.height );
        }
    }
}

function mouseDown(eve) {
    mouseIsDown = 1;
    var pos = getMousePos(canvas, eve);
    startX = endX = pos.x;
    startY = endY = pos.y;
    if(currShape=='rectangle')
    {
        drawSquare( canvas ); //update on mouse-up
    }
}

function mouseXY(eve) {
    if (mouseIsDown !== 0) {
        var pos = getMousePos(canvas, eve);
        endX = pos.x;
        endY = pos.y;
        drawSquare( cnvHid, true );
    }
}

function drawSquare( cnv, clear ) {
    var ctx = cnv.getContext( "2d" );
    if( clear && clear === true ){
        ctx.clearRect( 0, 0, cnv.width, cnv.height );
    }
    // creating a square
    var w = endX - startX;
    var h = endY - startY;
    var offsetX = (w < 0) ? w : 0;
    var offsetY = (h < 0) ? h : 0;
    var width = Math.abs(w);
    var height = Math.abs(h);

    ctx.beginPath();
    ctx.globalAlpha=0.7;
    ctx.rect(startX + offsetX, startY + offsetY, width, height);
    ctx.fillStyle = x;
    ctx.fill();
    ctx.lineWidth = y;
    ctx.strokeStyle = x;
    ctx.stroke();
    ctx.closePath();
}

function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
        x: evt.clientX - rect.left,
        y: evt.clientY - rect.top
    };
}

function renderAllCanvas(){
    var cnxRender = cnvRender.getContext( "2d" );
    cnxRender.drawImage(
        canvas
        ,0,0
        ,cnvRender.width,cnvRender.height
    );
    cnxRender.drawImage(
        cnvHid
        ,0,0
        ,cnvRender.width,cnvRender.height
    );
}

This is your new HTML

<!DOCTYPE HTML>
<html>
    <body onload="init()">
        <div class="canvasbody">
        <canvas id="can" width="400" height="400" style="display: none;"></canvas>
        <canvas id="canHid" width="400" height="400" style="display: none;"></canvas>
        <canvas id="canRend" width="400" height="400" style="border:1px dotted #eee;"></canvas>
        </div>
    </body>
</html>

Related


How to draw circle on canvas when mouse moves

books I am trying to draw a circle on the canvas with mouse movement, but without success. My code is as follows: var damages_canvas = document.getElementById('damages-area'); var ctx_damages = damages_canvas.getContext('2d'); var circle_rect = damages_canvas.

Rectangle on canvas mouse over chart

mondo Iterates plotDatato create a rect around some values on the chart based on a condition. plotData.forEach( (each, index) => { if ( each.a > each.b ) { try { ctx.beginPath(); ctx.fillStyle = 'yellow'; ctx.rec

Tkinter resize rectangle on Canvas with mouse

guest 1 I want to create a simple GUI image labeling tool in Tkinter for my research project. Currently I have working code that loads images from a directory and can draw multiple bounding boxes. I would like to modify the code so that the rectangle BB can be

Image flickers when mouse moves in HTML canvas

Agibi I've looked at these threads 1 and 2 , but the flickering still occurs when the mouse is moved. my code: function draw(){ var img = new Image(); img.src = "/Sample/Icons/sample.png"; img.onload = function () { ctx.drawImage

Image flickers when mouse moves in HTML canvas

Agibi I've looked at these threads 1 and 2 , but the flickering still occurs when the mouse is moved. my code: function draw(){ var img = new Image(); img.src = "/Sample/Icons/sample.png"; img.onload = function () { ctx.drawImage

Display rectangle on canvas when mouse moves

Ajay Thakur I want to draw rectangle on canvas. The code below works fine, except when I draw the rectangle, it doesn't show the path when the mouse moves. When I leave the mouse, the rectangle is visible on the canvas. please help, thanks var canvas, ctx, fla

Display rectangle on canvas when mouse moves

Ajay Thakur I want to draw rectangle on canvas. The code below works fine, except when I draw the rectangle, it doesn't show the path when the mouse moves. When I leave the mouse, the rectangle is visible on the canvas. please help, thanks var canvas, ctx, fla

How to draw circle on canvas when mouse moves

books I am trying to draw a circle on the canvas with mouse movement, but without success. My code is as follows: var damages_canvas = document.getElementById('damages-area'); var ctx_damages = damages_canvas.getContext('2d'); var circle_rect = damages_canvas.

How to draw circle on canvas when mouse moves

books I am trying to draw a circle on the canvas with mouse movement, but without success. My code is as follows: var damages_canvas = document.getElementById('damages-area'); var ctx_damages = damages_canvas.getContext('2d'); var circle_rect = damages_canvas.

How to draw circle on canvas when mouse moves

books I am trying to draw a circle on the canvas with mouse movement, but without success. My code is as follows: var damages_canvas = document.getElementById('damages-area'); var ctx_damages = damages_canvas.getContext('2d'); var circle_rect = damages_canvas.

How to draw circle on canvas when mouse moves

books I am trying to draw a circle on the canvas with mouse movement, but without success. My code is as follows: var damages_canvas = document.getElementById('damages-area'); var ctx_damages = damages_canvas.getContext('2d'); var circle_rect = damages_canvas.

Rectangle on canvas mouse over chart

mondo Iterates plotDatato create a rect around some values on the chart based on a condition. plotData.forEach( (each, index) => { if ( each.a > each.b ) { try { ctx.beginPath(); ctx.fillStyle = 'yellow'; ctx.rec

Tkinter resize rectangle on Canvas with mouse

guest 1 I want to create a simple GUI image labeling tool in Tkinter for my research project. Currently I have working code that loads images from a directory and can draw multiple bounding boxes. I would like to modify the code so that the rectangle BB can be

Tkinter resize rectangle on Canvas with mouse

guest 1 I want to create a simple GUI image labeling tool in Tkinter for my research project. Currently I have working code that loads images from a directory and can draw multiple bounding boxes. I would like to modify the code so that the rectangle BB can be

Rectangle on canvas mouse over chart

mondo Iterates plotDatato create a rect around some values on the chart based on a condition. plotData.forEach( (each, index) => { if ( each.a > each.b ) { try { ctx.beginPath(); ctx.fillStyle = 'yellow'; ctx.rec

Tkinter resize rectangle on Canvas with mouse

guest 1 I want to create a simple GUI image labeling tool in Tkinter for my research project. Currently I have working code that loads images from a directory and can draw multiple bounding boxes. I would like to modify the code so that the rectangle BB can be

Display rectangle on canvas when mouse moves

Ajay Thakur I want to draw rectangle on canvas. The code below works fine, except when I draw the rectangle, it doesn't show the path when the mouse moves. When I leave the mouse, the rectangle is visible on the canvas. please help, thanks var canvas, ctx, fla

Display rectangle on canvas when mouse moves

Ajay Thakur I want to draw rectangle on canvas. The code below works fine, except when I draw the rectangle, it doesn't show the path when the mouse moves. When I leave the mouse, the rectangle is visible on the canvas. please help, thanks var canvas, ctx, fla

Image flickers when mouse moves in HTML canvas

Agibi I've looked at these threads 1 and 2 , but the flickering still occurs when the mouse is moved. my code: function draw(){ var img = new Image(); img.src = "/Sample/Icons/sample.png"; img.onload = function () { ctx.drawImage

Image flickers when mouse moves in HTML canvas

Agibi I've looked at these threads 1 and 2 , but the flickering still occurs when the mouse is moved. my code: function draw(){ var img = new Image(); img.src = "/Sample/Icons/sample.png"; img.onload = function () { ctx.drawImage

Display rectangle on canvas when mouse moves

Ajay Thakur I want to draw rectangle on canvas. The code below works fine, except when I draw the rectangle, it doesn't show the path when the mouse moves. When I leave the mouse, the rectangle is visible on the canvas. please help, thanks var canvas, ctx, fla

How to draw circle on canvas when mouse moves

books I am trying to draw a circle on the canvas with mouse movement, but without success. My code is as follows: var damages_canvas = document.getElementById('damages-area'); var ctx_damages = damages_canvas.getContext('2d'); var circle_rect = damages_canvas.

How to draw circle on canvas when mouse moves

books I am trying to draw a circle on the canvas with mouse movement, but without success. My code is as follows: var damages_canvas = document.getElementById('damages-area'); var ctx_damages = damages_canvas.getContext('2d'); var circle_rect = damages_canvas.

How to draw circle on canvas when mouse moves

books I am trying to draw a circle on the canvas with mouse movement, but without success. My code is as follows: var damages_canvas = document.getElementById('damages-area'); var ctx_damages = damages_canvas.getContext('2d'); var circle_rect = damages_canvas.

How to draw circle on canvas when mouse moves

books I am trying to draw a circle on the canvas with mouse movement, but without success. My code is as follows: var damages_canvas = document.getElementById('damages-area'); var ctx_damages = damages_canvas.getContext('2d'); var circle_rect = damages_canvas.

Rectangle on canvas mouse over chart

mondo Iterates plotDatato create a rect around some values on the chart based on a condition. plotData.forEach( (each, index) => { if ( each.a > each.b ) { try { ctx.beginPath(); ctx.fillStyle = 'yellow'; ctx.rec

Fabric.js - How to detect canvas when mouse moves?

Mullainathan In my fabricjs app I create dynamic canvas (variables are also dynamic). Here I need to detect a specific canvas when the mouse moves on the canvas. sample code, var i = 0, canvasArray = []; $(this).find('canvas').each(function() { i++; va

How to draw circle on canvas when mouse moves

books I am trying to draw a circle on the canvas with mouse movement, but without success. My code is as follows: var damages_canvas = document.getElementById('damages-area'); var ctx_damages = damages_canvas.getContext('2d'); var circle_rect = damages_canvas.