Skip to content Skip to sidebar Skip to footer

Flipping An Array Of Points As A Shape Around Its Center Vertically Or Horizontally

I have a web app that receives some array of points and I need to draw them on a canvas. Unfortunately, I get the dataset not the way I want. I need to rotate the shapes 180 degree

Solution 1:

To find the mid-point, do something like:

let shape = [{x: 10, y:10}, {x: 30, y:10}, {x: 20, y:30}];

functiongetMinMax({min, max}, shape) {
    if (shape.y < min) {min = shape.y;}
    if (shape.y > max) {max = shape.y;}
    return {min, max}
}

var initValues = {min: Infinity, max: -Infinity};
var {min, max} = shape.reduce(getMinMax, initValues);
console.log("min y: " + min + ", max y: " + max);

This gives you the min/max values in y. Then:

let x = (max-min)*2;
let flipped = { x: point.x, y: x - point.y };

which should then change 10, 10, 30 into 30, 30, 10

Solution 2:

What you're doing in your picture is more than flipping the coordinates. It's flipping them and then arbitrarily repositioning them.

Here's flipping the points:

// Main template shapelet shape = [{x: 10, y:10}, {x: 30, y:10}, {x: 20, y:30}];

    let canvas = {}; // Canvas to draw onlet ctx = {}; // Context of the Canvas// Init elements
    $( document ).ready(function() {
        canvas = document.getElementById("myCanvas");
        ctx = canvas.getContext("2d");
        drawShape();
    });

    // Draw the templatefunctiondrawShape() {
        
        
        // Original shape
        ctx.save();
        ctx.beginPath();
        ctx.strokeStyle = 'green';
        ctx.fillStyle = 'green';
        for(let point of shape) {
            ctx.lineTo(point.x, point.y);
        }
        ctx.closePath();
        ctx.fill();
        ctx.stroke();

        ctx.restore();
        

         // Flipped shape
        ctx.save();
        let flippedShape = flipVertical(shape);
        
        ctx.beginPath();
        ctx.strokeStyle = 'red';
        ctx.fillStyle = 'red';
        for(let point of flippedShape) {
            ctx.lineTo(point.x, point.y);
        }
        ctx.closePath();
        ctx.fill();
        ctx.stroke();

        ctx.restore();

        
        
        
    }
    
    functionflipVertical(points) {
      let ret = [];
      var min_x, min_y;
      for(point of points) {
        let flipped = { x: canvas.width - point.x, y: canvas.width - point.y };
        ret.push(flipped);
      }
      
      return ret;
    }
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script><canvasid="myCanvas"width="100"height="100"style="border:1px solid #000000;"></canvas>

Post a Comment for "Flipping An Array Of Points As A Shape Around Its Center Vertically Or Horizontally"