Search code examples
javascriptcanvasdrawingcoordinatespaperjs

Paper.js, gap between cursor and canvas


I am trying to build a simple drawing app with Paper.js. I can draw with the mouse but I have a gap between the cursor and the line drawn on the canvas.

I have realised that the navigation menu on top of the webpage is pushing down the cursor (100px) I assume that the mouse coordinates are taken from top-left (0-0) of the window and the same coordinates are used on the canvas which measured these points from its own top-left corner (see the screenshot). I have tried setting the canvas position to absolute, which helps to get it to the top left corer, but I need it in the center of the window.

How could I fix this?

Thanks!

enter image description here

script:

...
    var doc = $(document),
            win = $(window),
            canvas = $('#paper'),
            ctx = canvas[0].getContext('2d')

    doc.on('mousemove',function(e){
            if($.now() - lastEmit > 30){
                socket.emit('mousemove',{
                    'x': e.pageX,
                    'y': e.pageY,
                    'drawing': drawing,
                    'id': id                
                });

                lastEmit = $.now();
            }

            // Draw a line for the current user's movement, as it is
            // not received in the socket.on('moving') event above
            // (because he only broadcats (not receiving))

            if(drawing){

                drawLine(prev.x, prev.y, e.pageX, e.pageY);

                prev.x = e.pageX;
                prev.y = e.pageY;
            }
        });




        function drawLine(fromx, fromy, tox, toy){
            console.log(fromy + ' ' + toy);

            ctx.moveTo(fromx, fromy);
            ctx.lineTo(tox, toy);
            ctx.stroke();
        }

Solution

  • I can repro your issue by using an early version of paperjs - notably this version is the one on jsfiddle. I see the lines offset the way you do with v 0.22 and then correctly rendered with version 0.9.25. Here's my code:

    <!-- fails -->
    <script type='text/javascript' src='http://cdnjs.cloudflare.com/ajax/libs/paper.js/0.22/paper.js'></script>
    
    <!-- works --> <!--
    <script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.9.25/paper-full.js'></script>
    -->
    
    <style type='text/css'>
        #canvas1{
            height: 400px;
            width: 400px;
            border: 1px solid black;
        }
    </style>
    
    <script type='text/javascript'>
        paper.install(window);
    
        window.onload = function() {
            paper.setup('canvas1');
            var path = new Path();
            var tool = new Tool();
            path.strokeColor = 'black';
            tool.onMouseMove = function(event) {
                path.add(event.point);
            }
    
        }
    </script>