I’m trying to implement an application where when the user clicks on an image, the coordinates are being saved to variables, and the point of the click is highlighted in red.
For this matter I have written the following code:
Script:
<script lang="ts">
const img = `https://raw.githubusercontent.com/lieldvd/mturk/main/15545/frame_0.jpg`
const markerOffsetX = 24;
const markerOffsetY = 152;
$: outerWidth = 0
$: innerWidth = 0
$: outerHeight = 0
$: innerHeight = 0
const markLocation = (x: number, y: number) => {
console.log('Hello')
const mrkr = document.querySelector<HTMLElement>(".marker");
console.log('marking')
if (mrkr != null){
mrkr.style.left = String(x) + '%';
mrkr.style.top = String(y) + '%';
}
}
function onClick(event: any){
// Image container
var imageContainer = document.getElementsByClassName("videoContainer")[0].getBoundingClientRect();
const imageContainerWidth = imageContainer.width;
const imageContainerHeight = imageContainer.height;
const absoluteClickX = event.clientX;
const absoluteClickY = event.clientY;
console.log('innerW = ' + innerWidth);
console.log('outerW = ' + outerWidth);
console.log('innerH = ' + innerHeight);
console.log('outerH = ' + outerHeight);
console.log('absoluteClickX = ' + absoluteClickX);
console.log('absoluteClickY = ' + absoluteClickY);
let relX = 100 * absoluteClickX / innerWidth;
let relY = 100 * absoluteClickY / innerHeight;
console.log('relX = ' + relX )
console.log('relY = ' + relY )
markLocation(relX, relY);
}
</script>
Main:
<svelte:window bind:innerWidth bind:outerWidth bind:innerHeight bind:outerHeight />
<main>
<div class="videoContainer">
<h1><u>Training Guidelines</u></h1>
<h2>Welcome to the "Contact Tagging" Training</h2>
<!-- svelte-ignore a11y-no-noninteractive-element-interactions -->
<!-- svelte-ignore a11y-click-events-have-key-events -->
<img
class="videoCanvas"
src={img}
alt='Blank'
on:click|preventDefault={(e)=>onClick(e)}
/>
<span class="marker"></span>
</div>
</main>
Style:
<style>
main {
text-align: center;
padding: 0em;
max-width: 240px;
margin: 0 auto;
}
@media (min-width: 640px) {
main {
max-width: none;
}
}
.videoContainer{
/* This enables children to use position: absolute to be positioned using absolute coordinates relative to this element. */
position: relative;
}
.marker{
/* Here we position this element relative to the .container element. */
position: absolute;
left: -50%; /* Update this using JS when the user clicks. */
top: -50%; /* Update this using JS when the user clicks. */
/* left and top indicates the position of the top left corner. You probably want it to be centered at that position. So translate (move it) 50% of it's size up and to the left. */
transform: translate(-50%, -50%);
/* Make it look like a circle. */
width: 5px;
aspect-ratio: 1;
border-radius: 100%;
background-color: red;
}
</style>