Click here to Skip to main content
15,936,802 members
Please Sign up or sign in to vote.
3.50/5 (2 votes)
See more:
I am working on a project where I want to draw a rectangle when I double click on a canvas. I want to be able to double click the first time and a rectangle is drawn and when the I double click again on another place on the canvas for another rectangle to be drawn. Below is my JavaScript funtion that only draws one rectangle no matter how many times I double click on separate occasions. Please help.

JavaScript
function handleMouseDoubleClick(e) {

     alert('This will create shapes on the canvas');

     // create the rectangle
     var images = [];
     images.push({
         x: 200,
         y: 150,
         width: 25,
         height: 25,
         color: "gold"
     });

     // draw rectangle
     context.globalAlpha = 1.00;
     for (var i = 0; i < images.length; i++) {
         var img = images[i];
         context.beginPath();
         context.rect(img.x + panX, img.y + panY, img.width, img.height);
         context.fillStyle = img.color;
         context.fill();
         context.stroke();
     }
 }
Posted

What about taking into account the mouse position also?
Take a look on this nice tutorial: http://simonsarris.com/blog/510-making-html5-canvas-useful[^], it is about what you try to learn.
 
Share this answer
 
The x and y coordinates are fixed, so it kept drawing on the same place.
Study this sample code and adapt:
XML
<!DOCTYPE HTML>
<html>
<head>
<title>Coding Canvas</title>
</head>
<body>
<canvas id="mycanvas" width="350" height="200" style="border:1px solid #000000; margin:20px;">
    Oops! This browser does not support the HTML5 canvas tag.
</canvas>

<script>
var canvas=document.getElementById('mycanvas');
var context=canvas.getContext('2d');

function drawRec(x, y){
    context.beginPath();
    context.rect(x, y, 80, 50);
    context.stroke();
}

// get x, y coordinates of double clicking
function getPosition(e) {
    var rect = canvas.getBoundingClientRect();
    return {
        x: e.clientX - rect.left,
        y: e.clientY - rect.top
    };
}

// add event listener on double click to canvas
canvas.addEventListener('dblclick', function(e) {
    var position = getPosition(e);
    drawRec(position.x, position.y);
});
</script>

 </body>
</html>

Read more: Beginner's Guide to HTML5 & CSS3 - Coding Canvas[^]
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 27-Jan-15 16:34pm    
5ed. This comprehensive sample can certainly be used for the prototype.
—SA
Peter Leow 27-Jan-15 19:28pm    
Thank you, Sergey.
I assume your code is working and panX, panY and context are being define some other place.

From looking at the code, every time there is a double click on the canvas the rectangle is being re-drawn over itself.
I assume the panX and panY are being populated and should represent the mouse position somehow, which does not appear to be working in your example.

I have modified the code to get it to work using jQuery.
CSS
#canvas {border:solid 1px green;}

HTML
<canvas id="canvas" width="300" height="300"></canvas>

JavaScript
$(document).ready(function () {
    var context = $('#canvas')[0].getContext('2d');

    $('#canvas').dblclick(function (e) {
        //get canvas offset
        var offset = $(this).offset();

        // create the rectangle
//note only one image being put in here so no need to loop later
        var images = [];
        images.push({
            //use mouse x and y position and offset
            x: e.clientX - offset.left,
            y: e.clientY - offset.top,
            width: 25,
            height: 25,
            color: "gold"
        });

        // draw rectangle
        context.globalAlpha = 1.00;
//        for (var i = 0; i < images.length; i++) {
            //var img = images[i];
            var img = images[0];
            context.beginPath();
            context.rect(img.x, img.y, img.width, img.height);
            context.fillStyle = img.color;
            context.fill();
            context.stroke();
//        }
    });
});


Revisited:
JavaScript
//for javascript only version, remove jQuery code, and replace with javscript only code
$(document).ready(function () {
    var context = $('#canvas')[0].getContext('2d');
 
    $('#canvas').dblclick(function (e) {
        var offset = $(this).offset();
 
		//...code goes here...
		
    });
});

//for a javascript only version - no jQuery
window.onload=function(){
    var EleCanvas = document.getElementById('canvas');
    var context = EleCanvas.getContext('2d');

    EleCanvas.addEventListener('dblclick', function(e) {
        var offset = this.getBoundingClientRect();

		//...code goes here...
		
    });
};
//note: earlier version of Internet Explorer will not work using the addEventListener
//getBoundingClientRect may return different results for different browsers
 
Share this answer
 
v3
Comments
Sergey Alexandrovich Kryukov 27-Jan-15 16:35pm    
What's the point of using jQuery if you are not really using it? (Will you say: "$(document).ready..."? Well, well...) And globalAlpha is 1 by default. Why not setting line width, color, all that, why only alpha?
—SA
jaket-cp 28-Jan-15 4:30am    
Got your point on the $(document).ready.
Mainly using jQuery for the $(this).offset() side of things :)

On the other parts of code, just modified OP code as less as possible so they can see what is happening.

But thanks for the advice :)
Sergey Alexandrovich Kryukov 28-Jan-15 11:39am    
No problem.
For example, no need to write document.getElementById("canvas"), because jQuery will give you a wrapper via
canvas = $("#canvas");
and so on...
—SA
jaket-cp 28-Jan-15 11:49am    
Just notice in my code, not even referencing #canvas but canvas instead, oops.
Will revisit again :)
P.C Shabangu 28-Jan-15 7:08am    
Thanks fellow developers. We tried all these and they worked the way we wanted them to. Thnk u.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900