Mouse Postion
by linzoey
CSS
html{
background-color:blue;
margin:0;
}
body{
margin:0;
background-color:silver;
}
JavaScript
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
move(xDistance, yDistance) {
return new Point(this.x + xDistance, this.y + yDistance);
}
moveByAngle(angle, distance) {
let r = (angle * Math.PI) / 180;
return new Point(
this.x + distance * Math.sin(r),
this.y + distance * Math.cos(r)
);
}
distance(point2) {
let point1 = new Point(this.x, this.y)
let a = point1.x - point2.x
let b = point1.y - point2.y
if (a < 0) {
a = a - (a * 2)
}
if (b < 0) {
b = b - (b * 2)
}
let toSquare = (b ** 2) + (a ** 2)
return Math.sqrt(toSquare)
}
}
var draw = SVG().addTo('body').size(800, 630)
let rect=draw.rect(200,200).move(200,200).fill(new SVG.Color({ h: 160, s: 100, l: 50 })).stroke({width:2,color:'black'})
let mouse=new Point(10,10);
let xText=draw.text('X: '+JSON.stringify(mouse.x)).move(10,80)
let yText=draw.text('Y: '+JSON.stringify(mouse.y)).move(10,120)
let scrollPosition=new Point(0,0)
document.addEventListener('scroll', ((e) => {
mouse.x = mouse.x+(window.scrollX-scrollPosition.x)
mouse.y = mouse.y + (window.scrollY - scrollPosition.y)
scrollPosition = new Point(window.scrollX,window.scrollY)
xText.plain('X: '+JSON.stringify(mouse.x))
yText.plain('Y: '+JSON.stringify(mouse.y))
console.log (mouse)
}))
document.addEventListener('pointermove', ((e) => {
mouse.x = e.pageX
mouse.y = e.pageY
xText.plain('X: '+JSON.stringify(mouse.x))
yText.plain('Y: '+JSON.stringify(mouse.y))
console.log (mouse)
}))