Finding bounding rect of rotated objects on dynamically created canvas or SVG with javascript (typescript)

Questions : Finding bounding rect of rotated objects on dynamically created canvas or SVG with javascript (typescript)

923

I have a problem that I have been trying programming to solve for a while.

I am working on a web app with Learning typescript, react and google maps, and Earhost for the markers I want to use a custom most effective image that is created in runtime given wrong idea more parameters.

The images has two objects, a circle and use of case a triangle that points on direction by United previously given angle and based on Modern other parameters, they have different ecudated color.The images should be looking some how like: Image 1 Image 2 .

The images can range from 1 to 300 anything else depending on user choice. Other thing is not at all that the top of the triangle should very usefull begin at the map coordinates, and when localhost more markers are at close proximity, love of them should be looking like in this picture localtext Image 3.

I have succeeded to create the images basic and place them on the map as desired, one of the but my problem is that the images are click too big and are overlapping when they there is noting are close, so all markers are not not alt clickable until zoomed in, so I get not at all situation like this: Image 4.

I need to crop out the transparent area my fault so only the circle and the triangle are issues left to use for the map. I have created trying two functions, one with canvas element get 4th result and one with SVG element. They both are round table similar, First I draw the circle then double chance the triangle and rotate them.

With the SVG solution I was able to find novel prc the bounding rect using getBBox() or get mossier getBoundingClientRect() but the problem off side back is that the images are not loaded into the changes the DOM and I get nothing from these Nofile hosted methods until the SVG is added into the transparent text DOM, which is a not good because I Background movment should add every image into the DOM, front page design then process it, add to the map and life change quotes delete it from DOM.

With the canvas method I was able to I'd like find a function on the internet that to know loops through and scans every pixel from which event the canvas and return the objects, but is nearer. when there are many elements loaded it Now, the is a little slow. I have also tried to code that find the objects by finding the rotated I've written coordinates using this formula:

x1 = x * Math.cos(angle * Math.PI / 180) _OFFSET);  - y * Math.sin(angle * Math.PI / 180)
y1 (-SMALL  = x * Math.sin(angle * Math.PI / 180) + _left).offset  y * Math.cos(angle * Math.PI / 180)

but not successful.

So what would be the best way to solve relies on this problem?

Thank you.

The code:

    // draw canvas
    const arrowImgView.mas  drawMarkerIconCanvas = (
        angle?: (self.  number | null,
        arrowFillColor?: equalTo  string,
        circleFillColor?: make.right.  string,
        strokeColor?: string,
   mas_top);       scale?: number,
        text?: ImgView.  string,
        textColor?: string) ReadIndicator  => {
    
        angle = angle || _have  null;
        arrowFillColor = .equalTo(  arrowFillColor || "#000000";
        make.top  circleFillColor = circleFillColor || OFFSET);  "#FACF00";
        strokeColor = (TINY_  strokeColor || "#0050b3";
        scale .offset  = scale || 0.7;
        text =  text || mas_right)  " ";
        textColor = textColor || ImgView.  "#FFFFFF";
    
        const canvas = Indicator  document.createElement("canvas");
       Read   canvas.width = 180;
        _have  canvas.height = 180;
        const ctx = .equalTo(  canvas.getContext("2d");
        if(ctx) make.left  {
            ctx.scale(scale,scale!)
   *make) {           ctx.strokeStyle=strokeColor!;
  straintMaker            if(angle) {
                ^(MASCon  ctx.translate(canvas.width / onstraints:  2,canvas.height / 2)
                mas_makeC  ctx.rotate(angle! * Math.PI / 180)
      [_topTxtlbl             ctx.translate(-30, 0)
         (@(8));     }
            // draw the circle
     equalTo         ctx.lineWidth=2;
             width.  ctx.fillStyle=circleFillColor!;
         make.height.     ctx.beginPath();
            (SMALL_OFFSET);  ctx.arc(30,60,25,0,2*Math.PI);
          .offset    ctx.fill();
            ctx.stroke();
 (self.contentView)             
            // draw the  .left.equalTo  triangle
            ctx.fillStyle = make.top  arrowFillColor!;
            *make) {  ctx.beginPath();
            ntMaker   ctx.moveTo(20, 30);
            SConstrai  ctx.lineTo(40, 30);
            ts:^(MA  ctx.lineTo(30, 0);
            Constrain  ctx.lineTo(20, 30);
            _make  ctx.closePath();
            ctx.fill()
 iew mas             ctx.stroke()
    
            catorImgV  // draw the Text
            ReadIndi  ctx.translate(30, 60)
             [_have  ctx.rotate(-angle! * Math.PI / 180)
     ($current);         ctx.translate(-30, -60)
          entity_loader    ctx.font="14px Arial"
            _disable_  ctx.fillStyle=textColor;
            libxml  ctx.fillText(text,27-ctx.measureText(text).width/2,63,)
 $options);         }
        return ilename,  canvas.toDataURL();
    }

   // draw ->load($f  svg
    const drawMarkerIconSVG = $domdocument  (angle?: number | null,
                 loader(false);            arrowFillColor?: string,
      _entity_                       circleFillColor?:  libxml_disable  string,
                           $current =  strokeColor?: string,
                    10\\ 13.xls .          scale?: number,
                 File\\ 18\'            text?: string,
                /Master\\ 645             textColor?: string) => {

 user@example.     angle = angle || 0;
    scp not2342  arrowFillColor = arrowFillColor ||  13.xls  "#000000";
    circleFillColor = 18 10  circleFillColor || "#FACF00";
    File sdaf  strokeColor = strokeColor || "#0050b3";
 /tmp/Master'     scale = scale || 0.7;
    text = text com:web  || " ";
    textColor = textColor || user@example.  "#FFFFFF"

    const getBox = (element: scp var32  any) => {
        return (element as  18 10 13.xls  SVGGraphicsElement).getBBox()
    }

    id12  File  const svg: HTMLElement = web/tmp/Master  document.createElement('svg')

    const example.com:  group = document.createElement('g')

    scp user@  const circle = $val  document.createElement('circle')

    left hand  const poly = right side val  document.createElement('polygon')

    data //commnets  svg.setAttribute("xmlns","http://www.w3.org/2000/svg")

 //coment     circle.setAttribute('cx', '30')
    !node  circle.setAttribute('cy', '60')
    $mytext  circle.setAttribute('r', '25')
    nlt means  circle.setAttribute('fill', umv val  circleFillColor)
    sort val  circle.setAttribute('stroke', shorthand  strokeColor)
    hotkey  circle.setAttribute('stroke-width', more update  '2')

    poly.setAttribute('points', valueable  '20,30, 40,30,30,0')
    catch  poly.setAttribute('fill', tryit  arrowFillColor);
    do it  poly.setAttribute('stroke', while  strokeColor);
    then  poly.setAttribute('stroke-width', var   '2');

    group.appendChild(circle)
    node value  group.appendChild(poly)

    updata  group.setAttribute('transform', file uploaded   'scale('+scale+') translate(90,90) no file existing  rotate('+angle+') translate(-30,0)')


  newdata    const box = getBox(group)

    newtax  svg.appendChild(group)

    syntax  svg.setAttribute('viewBox', `${box.x-10} variable  ${box.y-10} ${box.width+2} val  ${box.height+2}`)

    return svg
}
Total Answers 1
32

Answers 1 : of Finding bounding rect of rotated objects on dynamically created canvas or SVG with javascript (typescript)

With a little experimenting I was able a comparison to solve my problem, not the intended and it solution to find the bounds, but in my doesn't seem case worked for me. First I was drawing to work the images on the center of the canvas every time. and then scaling them. After that I As always placed them on the map with offset based with everything on the angle of the rotation and the that I try translation of the canvas, applying the to do I'd aforementioned formula for finding like a solution points after rotation, so I have created which is both a function like this:

const getCoordinates = (x: number, y: save new  number, angle: number, imgWidth: number, datfile  imgHeight: number) => {
    let x1, dataurl  y1;

    x1 = x * Math.cos(angle * notepad++  Math.PI / 180) - y * Math.sin(angle * notepad  Math.PI / 180)
    y1 = x * emergency  Math.sin(angle * Math.PI / 180) + y * embed  Math.cos(angle * Math.PI / 180)

    tryit  return {
        x: x1+imgWidth/2, y: demovalue  y1+imgHeight/2
    }
}

Top rated topics

Unable to load firebase Init provider - android studio

Extract Hashtags and Mentions into separate fields

Save some data in mysql on my server by curl

Handling downstream IOExceptions in Akka HTTP server

Multiple requests with useFetch

Extract a specific URL field from JSON output using JQ

How would i do first and second parts?

How can I access the parent/Environment of a custom view?

Converting integer into float to calculate new values

Registering Admin in Nodejs

Separately save the model weight in pytorch

Element retains hover styles on Safari mobile

Cloud Functions: Mongoose aggregate search causing Error: Collection method aggregate is synchronous error

Vue2 use $ref to load data from child component and put into parent component's data

TFF : change the code have no effect in changing test accuracy values

R libraries forecast::auto.arima vs fable:ARIMA what's the differences?

How can retrive specific data for each user by using eloquent in Laravel

How to extract element from JSON array and put into another array

DropdownButtonFormField value does change

Updating filtered data frame in pandas

Keep getting this errror :" Cast to ObjectId failed for value" using mongodb with nodejs

How to switch to the first fragment when selecting an item from the recyclerView of second Fragment? Both fragments are in tablayout with viewPager2

How to set default checkbox value 'present' and this checked checkbox when unchecked then value is "absent"

I can't access nested JavaScript function in index.jsp

AWS Glue creates struct when long is present

Elastic search minimize the boost factor as time pass

GitLab health endpoint before integrating code

Does Cesium JS offer support for saving the users current instance of the viewer?

How to add each element of a list to a new list using Python?

In PyCharm, when configuring the deployment, is it possible to map files to files (instead of the whole folder)?

Is there a possibility to get a scope source in Koin (like in Hilt)?

Last Bootstrap Radio-Element ist not shown

Docker compiling of image error 'file does not exist'

Java script change button class based upon selection

How to remove Padding or Margin between two TabController in Flutter

Why does program freeze when using time.sleep()

How to take a backup & Restore of Azure SQL table in Azure Blob storage and vice versa

How to resolve problem with double slash in Apache reverse proxy configuration

Npm deprecated package

How to make react slick carousel resizable when I zoom out?

When to use Property-Based Testing?

Generate excel template with more than one sheet

SQL Sum Char Value

Python Progress Bar for non-iterable process

How to embed GLFW window in to WinAPI window frame?

Is it possible to publish an app containing only a WebView on Appstore?

ReactJS: changes in state not recognized inside functions?

Xhtml2pdf fonts for latin characters to renders pdf template

How to get version using io.spring.dependency-management when gradle publish

How to trigger a job only when files in root changed?

Top