Getting Mouse Position using RxJS

Introduction

This will be a short post just to demo some basic event capturing using RxJS.

Requirement

We want to capture mouse coordinates on the screen and use those values to move a shape around. You can use it for other effects as fit for your requirements.

Code

HTML

First lets define a draw a circle on web-page using following markup and CSS

Subscriber Content

RxJS

now in corresponding component file, add following code

Code is pretty much self explanatory. Let me know if you have some questions.

With this in-place, we can run the application and check the output.

Output

Now, if we move the mouse on screen, the circle will move along and we can also see the x,y values in the console.

Adding more RxJS Operators

We can add more RxJS operators in the mix. Following is updated code which performing some filtering and adding delay using RxJS:

Property Binding

We can also use property binding as follows

So, we have defined a property name coordinates which is updated when mouse is moved. This property can be now bound to HTML elements as follows:

and the output is as follows

Summary

This was a simple and short example of RxJS usage. Till next time, Happy Coding.


Discover more from Hex Quote

Subscribe to get the latest posts sent to your email.

Discover more from Hex Quote

Subscribe now to keep reading and get access to the full archive.

Continue reading