Responsive mouse events with canvas?

0

I have the following code:

var block = false;
var context;
var drawing;
var rect;

$(function() {
    context = $('#canvas')[0].getContext('2d');
    drawing = false;
    rect = $('#canvas')[0].getBoundingClientRect();

    $('#canvas').mousedown(function (evt) {
        if(!block) {
            context.moveTo(evt.clientX - rect.left, evt.clientY - rect.top);
            drawing = true;
        }
    });

    $('#canvas').mouseup( function () {
        if(!block)
            drawing = false;
    });

    $('#canvas').mousemove(function (evt) {
        if (drawing && !block) {
            context.lineTo(evt.clientX - rect.left, evt.clientY - rect.top);
            context.stroke();
        }
    });

});
#canvas {
    height:  100%;
    width: 100%;
    background-color: rgb(230, 230, 230);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><canvasid="canvas" height="500" width="750"></canvas>

When testing the code, note that clicking and moving the mouse by canvas a drawing is done, but the drawing is done a little far from the cursor, it is only done in the right place when the screen is enlarged. How do I turn this responsive? Regardless of the screen, draw the exact mouse location on canvas ? Note that canvas does not occupy the entire screen because I have more things on the screen

    
asked by anonymous 21.11.2016 / 16:23

1 answer

0

Removing

height:  100%;
width: 100%;

It worked perfectly here

var block = false;
var context;
var drawing;
var rect;

$(function() {
    context = $('#canvas')[0].getContext('2d');
    drawing = false;
    rect = $('#canvas')[0].getBoundingClientRect();

    $('#canvas').mousedown(function (evt) {
        if(!block) {
            context.moveTo(evt.clientX - rect.left, evt.clientY - rect.top);
            drawing = true;
        }
    });

    $('#canvas').mouseup( function () {
        if(!block)
            drawing = false;
    });

    $('#canvas').mousemove(function (evt) {
        if (drawing && !block) {
            context.lineTo(evt.clientX - rect.left, evt.clientY - rect.top);
            context.stroke();
        }
    });

});
#canvas {
    background-color: rgb(230, 230, 230);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><canvasid="canvas" height="500" width="750"></canvas>
    
21.11.2016 / 16:54