Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canvas element with offset

Draws nothing if the item is biased.

jsfiddle: http://jsfiddle.net/9UyxF/

JavaScript:

var ctx = document.getElementById("drawing").getContext("2d");

$("#drawing").mousemove(function(e) {
    ctx.lineTo(e.clientX, e.clientY);
    ctx.stroke();
});

var ctx_without_offset = document.getElementById("without_offset").getContext("2d");

$("#without_offset").mousemove(function(e) {
    ctx_without_offset.lineTo(e.clientX, e.clientY);
    ctx_without_offset.stroke();
});

CSS:

#drawing {
    border: 1px solid #000;
    position: absolute;
    top: 50px;
    right: 0;
}
#without_offset {
    border: 1px solid #000;
}

How to fix it? Thanks in advance.

like image 683
owl Avatar asked Nov 04 '25 21:11

owl


1 Answers

The coordinates on the canvas, and cooridnates of clientX and clientY have different origins. This version realigns them:

function makeDrawFunction(elem) {
    var context = elem.getContext('2d');
    return function(e) {
        var offset = $(elem).offset();
        context.lineTo(e.clientX - offset.left, e.clientY - offset.top);
        context.stroke();
    }
}


$("#drawing").mousemove(makeDrawFunction(
  document.getElementById("drawing")
));

$("#without_offset").mousemove(makeDrawFunction(
  document.getElementById("without_offset")
));

live demo

like image 103
sabof Avatar answered Nov 07 '25 15:11

sabof



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!