Responsive mouse events with canvas?

Asked

Viewed 117 times

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>


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

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

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>


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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.