DEKKER
DEKKER

Reputation: 911

Rotate a shape as array of points on its origins

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 degrees. I have no idea how to do this...

Please see the example in the snippet.

// Main template shape
let shape = [{x: 10, y:10}, {x: 120, y:10}, {x: 110, y:110}, {x: 50, y:175}];

let canvas = {}; // Canvas to draw on
let ctx = {}; // Context of the Canvas

// Init elements
$( document ).ready(function() {
    canvas = document.getElementById("myCanvas");
    ctx = canvas.getContext("2d");
    drawShape();
});

// Draw the template
function drawShape() {
    ctx.save();

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

    ctx.restore();
}
<!DOCTYPE html>
<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <title>Hahaha!</title>
</head>

<body>
<canvas id="myCanvas" width="200" height="200" style="border:1px solid #000000;"></canvas>
</body>
</html>

Upvotes: 0

Views: 30

Answers (1)

Orwellian Mentat
Orwellian Mentat

Reputation: 419

If I understand your question correctly, you want to turn the shape around by 180 degrees ? As in vertically invert it ? If this is it, here's a solution, you need an axis relative to which to turn it. Problem is if you just invert for every point (x,y), you put (x,-y), canvas being defined for only positive values it won't show on your screen, imagine it outstide the screen, you need to "push" it back down onto the canvas, you do this by adding the height of the canvas after having inverted the shape.

// Main template shape
let shape = [ {x:10, y:10}, {x:120, y:10}, {x:110, y:110}, {x:50, y:175} ];

let canvas = {}; // Canvas to draw on
let ctx = {}; // Context of the Canvas

// Init elements
$( document ).ready(function() {
    canvas = document.getElementById("myCanvas");
    ctx = canvas.getContext("2d");
    drawShape();
});

// Draw the template
function drawShape() {
    ctx.save();

    ctx.beginPath();
    ctx.strokeStyle = 'yellow';
    ctx.fillStyle = 'red';
    for(let i = 0; i < shape.length; i++) {
        ctx.lineTo(shape[i][0], -shape[i][1] + 200);
    }
    for(let point of shape) {

        ctx.lineTo(point.x, -point.y + 200);
    }
    ctx.closePath();
    ctx.fill();
    ctx.stroke();

    ctx.restore();
}
<!DOCTYPE html>
<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <title>Hahaha!</title>
</head>

<body>
<canvas id="myCanvas" width="200" height="200" style="border:1px solid #000000;"></canvas>
</body>
</html>

Upvotes: 1

Related Questions