I’m new to svetle, as a part of a project I need to calculate relative coordinated of a mouse click inside an image shown on screen.
As the size of the screen is not constant, I need to calculate relative coordinates, as opposed to the absolute, i.e., the onse from the top left corner, but the onse from the top left corner of the <div>
I place the image in.
My intuition is that I need to get the top-left corner C(x, y)
of the component, and calculate the point
p(x, y) = (x - X, y - Y)
, where X = C(x)
and Y = C(y)
.
For this matter I saw that I can bind a property called contentRect
, but I can’t find proper example as how to use it.
For now I only managed to get the height and width of the component, but not the top left corner
My code is below:
<script>
let width: number = 0;
let height: number = 0;
let C_x = 0;
let C_y = 0;
let mousePosition = {x: 0, y: 0};
function handleMousemove(event: any){
mousePosition.x = event.clientX - C_x;
mousePosition.y = event.clientY - C_y;
}
</script>
<main>
{#each [images[currentSlideItem]] as image, index}
<div
bind:clientWidth={width}
bind:clientHeight={height}
>
{width}, {height}
<img
transition:slide="{{delay:200}}"
src={image}
alt='Blank'
width="1080"
on:click|preventDefault={(e)=>handleMousemove(e)}
/>
</div>
{/each}
<div>The mouse position is ({mousePosition.x}, {mousePosition.y})</div>
<div class="carousel-buttons">
<button id="play" on:click={() => play()}>⏯</button>
<button id="pause" on:click={() => pause()}>⏸</button>
<button id="prev" on:click={() => prevImage()}>⏪</button>
<button id="next" on:click={() => nextImage()}>⏩</button>
</div>
</main>
Thanks in advance,
Michael