CreateJS / EaselJS

The Easel Javascript library provides a full, hierarchical display list, a core interaction model, and helper classes to make working with the HTML5 Canvas element much easier.
http://createjs.com/
MIT License
8.11k stars 1.97k forks source link

feat(stage): recalculate mouse coordinates #1076

Open stfujnkk opened 1 year ago

stfujnkk commented 1 year ago

When the canvas scrolls or zooms, the coordinates of the mouse relative to the canvas are not updated unless you move or click the mouse.

stfujnkk commented 1 year ago

Added an exposed method(stage.recalculatePointerPosition) to update the mouse coordinates.

stfujnkk commented 1 year ago

This is the test page that whether scrolling or zooming, mouseX and mouseY can be updated in time.

<!DOCTYPE html>
<html lang="en">

<head>
    <title>EaselJS demo: hitTest</title>
    <style>
        body {
            margin: 0;
            padding: 7px;
            background-color: rgba(255, 255, 255, 0);
        }

        canvas {
            border: solid 1px rgba(0, 0, 0, 0.05);
        }
    </style>
    <script src="easeljs.min.js"></script>
</head>

<body>
    <div>
        <div style="width:200px;height:200px;background-color:#999999;overflow:auto;">
            <canvas id="demoCanvas" width="600" height="300"></canvas>
        </div>
    </div>
    <script>
        var stage, circle;
        function init() {
            stage = new createjs.Stage("demoCanvas");
            circle = stage.addChild(new createjs.Shape());
            circle.graphics.beginFill("red").drawCircle(50, 50, 50);
            circle.x = 0;
            circle.y = 0;
            createjs.Ticker.on("tick", tick);
        }

        function tick(event) {
            circle.alpha = 0.2;
            stage.recalculatePointerPosition();
            if (circle.hitTest(stage.mouseX, stage.mouseY)) {
                circle.alpha = 1;
            }
            stage.update(event);
        }
        init();
    </script>
</body>

</html>
stfujnkk commented 1 year ago

Added an open method(stage.recalculatePointerPosition) to update the mouse coordinates.

If you do not want to add external interfaces, you can achieve the same effect by adding a listener for the resize and scroll events.