javascript – Why does the object disappear and it draws badly in jCanvas?


Hello everyone, I want to ask the question why my object disappears when I go out of the canvas , and why the rectangle is not drawn correctly when I move the mouse. I am attaching the code:

$(document).ready(function() {
    var $canvas = $('canvas');
    var rect = {};
    var drawing = false;
    var trigger = $('.rect');

    function _makeRect() {
        var startX = $('.coordinate_x').val();
        var startY = $('.coordinate_y').val();
        var width = $('.rect_width').val();
        var height = $('.rect_width').val();

           fillStyle: '#000',
           draggable: true,
           fromCenter: false,
           x: startX, y: startY,
           width: width, height: height

        console.log(startX, startY, width, height);

    $('.make_rect').on('click', _makeRect);

    $canvas.on('mousedown', _mousedown);
    $canvas.on('mouseup', _mouseup);
    $canvas.on('mousemove', _drawing);

    function _mousedown(e) {
        drawing = true;
        var startX = e.pageX - $canvas.offset().left;
        var startY = e.pageY - $canvas.offset().top;
        rect.x = startX;
        rect.y = startY;

    function _mouseup(e) {
        drawing = false;

    function _drawing(e) {
        var currentX = e.pageX - $canvas.offset().left;
        var currentY = e.pageY - $canvas.offset().top;
        if(drawing) {
               fillStyle: '#000',
               layer: true,
               name: 'box',
               fromCenter: false,
               x: rect.x, y: rect.y,
               width: currentX - rect.x, height: currentY - rect.y


I can only tell you part of the answer.

why the rectangle is not drawing correctly when moving the mouse.

Because you are constantly drawing your rectangle. The solution is quite simple – you just need to change the logic to the following:

  1. Click on the button -> drawing = true -> mouseDown event;
  2. when moving in the if (drawing) block, you need to keep the current values ​​of X and Y (for example, lastX and lastY) -> mouseMove event;
  3. Release the mouse button – drawing = false and the mouseUp event is triggered. In it, we must add the rendering logic using the saved values ​​lastX and LastY (well, startX and startY) and then clear them for further use;

What we get as a result: When mousedown – filled values ​​StartX and StartY, MouseMove – filled values ​​LastX and LastY. On mouseUp – all 4 variables for drawing the shape. However, this solution is not ideal – perhaps you want to see the rectangle itself as you draw.

Scroll to Top