1

I've made this example to show what my problem is: http://jsfiddle.net/GSRgf/

HTML

<canvas id="canvas" width="500" height="500"></canvas>
<div id="div"></div>

JS

$(function() {
var ctx=$('#canvas')[0].getContext('2d'); 
rect = {};
drag = false;

$(document).on('mousedown','#canvas',function(e){
    rect.startX = e.pageX - $(this).offset().left;
    rect.startY = e.pageY - $(this).offset().top;
    rect.w=0;
    rect.h=0;
    drag = true;
});

$(document).on('mouseup','#canvas',function(){
    drag = false;
});

$(document).on('mousemove','#canvas',function(e){
    if (drag) {
        rect.w = (e.pageX - $(this).offset().left)- rect.startX;
        rect.h = (e.pageY - $(this).offset().top)- rect.startY;
        ctx.clearRect(0, 0, 500, 500);
        ctx.fillStyle = 'rgba(0,0,0,0.5)';
        ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);
    }
});    
});

How is it possible to keep drawing the rectangle when the mouse is over the div?

Thanks!

ticktack
  • 63
  • 5

1 Answers1

1

Remove the "#canvas" selector for the mousemove and mouseup events. Edit the mousemove event to use $("#canvas") instead of $(this).

http://jsfiddle.net/GSRgf/3/

$(function() {
    var ctx=$('#canvas')[0].getContext('2d'); 
    rect = {};
    drag = false;

    $(document).on('mousedown','#canvas',function(e){
        rect.startX = e.pageX - $(this).offset().left;
        rect.startY = e.pageY - $(this).offset().top;
        rect.w=0;
        rect.h=0;
        drag = true;
    });

    $(document).on('mouseup',function(){
        drag = false;
    });

    $(document).on('mousemove',function(e){
        if (drag) {
            rect.w = (e.pageX - $("#canvas").offset().left)- rect.startX;
            rect.h = (e.pageY - $("#canvas").offset().top)- rect.startY;
            ctx.clearRect(0, 0, 500, 500);
            ctx.fillStyle = 'rgba(0,0,0,0.5)';
            ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);
        }
    });    
});
Louis Ricci
  • 20,804
  • 5
  • 48
  • 62
  • I've decided to go this way, although... Do you have any idea why doesn't it work in IE at all? (trying with IE10). – ticktack Jul 25 '13 at 14:43
  • @ticktack - In IE9 jQuery 1.10.1 doesn't seem to work at least in JSFiddle, switching to jQuery 1.9 fixed the issue (with IE9) for me http://jsfiddle.net/GSRgf/4/ I don't have IE10 though – Louis Ricci Jul 25 '13 at 14:47
  • Right, that fixed it in IE10 too. Thanks! – ticktack Jul 25 '13 at 14:57