ticktack
ticktack

Reputation: 63

HTML5 - Canvas, draw rectangle through div

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!

Upvotes: 1

Views: 2514

Answers (1)

Louis Ricci
Louis Ricci

Reputation: 21106

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);
        }
    });    
});

Upvotes: 1

Related Questions