I create a new blazor web app project like this: (https://i.sstatic.net/ejiES4vI.png)
It has 2 projects in 1 solution. When I wanted to get the mouse coordinates on the Client side of my project, I can't get them without JavaScript code. (I couldn't even get with js when the "Ineractive Render Mode" part set it to auto, but that's not the point.) What I want to do is draw SVG lines as seen in the YouTube link ( https://www.youtube.com/watch?v=SGmioUSrZXo ), but couldn't do it no matter what i tried, I'm not used to it because it's both server-side and client-side, I don't know what to do.
Client-side codes:
@page "/counter"@inject IJSRuntime JSRuntime<svg @ref="svgElement" width="100%" height="500px" style="border: 1px solid black;" @onmousedown="StartDrawing" @onmousemove="Draw" @onmouseup="StopDrawing"> @foreach (var line in lines) {<line x1="@line.StartX" y1="@line.StartY" x2="@line.EndX" y2="@line.EndY" stroke="black" stroke-width="2" /> }</svg>@code { private ElementReference svgElement; private bool isDrawing = false; private List<Line> lines = new List<Line>(); private Line? currentLine; private async void StartDrawing(MouseEventArgs e) { isDrawing = true; var position = await GetSvgCoordinates(e.ClientX, e.ClientY); currentLine = new Line { StartX = position.X, StartY = position.Y }; } private async void Draw(MouseEventArgs e) { if (isDrawing) { var position = await GetSvgCoordinates(e.ClientX, e.ClientY); currentLine!.EndX = position.X; currentLine!.EndY = position.Y; StateHasChanged(); } } private void StopDrawing(MouseEventArgs e) { if (isDrawing) { lines.Add(currentLine!); isDrawing = false; StateHasChanged(); } } private async Task<(double X, double Y)> GetSvgCoordinates(double clientX, double clientY) { var result = await JSRuntime.InvokeAsync<dynamic>("getSvgCoordinates", svgElement, clientX, clientY); return ((double)result.x, (double)result.y); } private class Line { public double StartX { get; set; } public double StartY { get; set; } public double EndX { get; set; } public double EndY { get; set; } }}Client-side js code(wwwroot/js/site.js):
window.getSvgCoordinates = (element, clientX, clientY) => { const svgRect = element.getBoundingClientRect(); return { x: clientX - svgRect.left, y: clientY - svgRect.top };};Server-side MainLayout.razor code:
@inherits LayoutComponentBase<div class="page"><div class="sidebar"><NavMenu /></div><main><div class="top-row px-4"><a href="https://learn.microsoft.com/aspnet/core/" target="_blank">About</a></div><script src="js/site.js"></script><article class="content px-4"> @Body</article></main></div><div id="blazor-error-ui"> An unhandled error has occurred.<a href="" class="reload">Reload</a><a class="dismiss">🗙</a></div>