Rotating element on canvas object, relative to parent - javascript

I'm trying to draw a pair of skis (two rectangles) on a skier (a square) at varying rotations. I don't quite understand how you line up rotated elements on a canvas as you rotate the whole canvas, not just the object.
At the moment I have this:
ctx.fillStyle = 'rgba(0,0,0,0.8)';
ctx.fillRect(0, 0, W, H);
ctx.fillStyle = skiier.color;
ctx.fillRect(skiier.x, skiier.y, skiier.width, skiier.height);
ctx.fillStyle = '#00f';
var angle = 20;
ctx.rotate(angle*Math.PI/180);
ctx.fillRect(skiier.x, skiier.y,100,10);
ctx.fillRect(skiier.x, skiier.y + 20,100,10);
ctx.rotate(-angle*Math.PI/180);
Which gives me this:
But what I'd like to do is the following:
Bearing in mind the x and y coords of the skier is constantly changing, how can I adjust and position the skis relative to him?
I have a demo here if it helps:
http://codepen.io/EightArmsHQ/pen/cfa7052ed205b664b066450910c830c5?editors=001

You should consider the context save, restore and translate as follows:
// ...
var angle = 20;
ctx.save(); // save the state of the ctx
ctx.translate(skiier.x, skiier.y); // translate your context point to be the same as skiier.
ctx.rotate(angle * Math.PI / 180);
ctx.fillRect(-25, 0, 100, 10); // You can draw from new context point.
ctx.fillRect(-25, 20, 100, 10); // Same here.
// Instead of rotating back, use restore()...
// Useful to restore all ctx options as they were before the save()
ctx.restore();

To rotate around a point: you need to translate context to the point, rotate context, translate context back.
For example...
ctx.fillStyle = 'rgba(0,0,0,0.8)';
ctx.fillRect(0, 0, W, H);
ctx.fillStyle = skiier.color;
ctx.fillRect(skiier.x, skiier.y, skiier.width, skiier.height);
ctx.fillStyle = '#00f';
var angle = 20;
ctx.translate(skiier.x, skiier.y);
ctx.rotate(angle*Math.PI/180);
ctx.translate(-skiier.x, -skiier.y);
ctx.fillRect(skiier.x, skiier.y,100,10);
ctx.fillRect(skiier.x, skiier.y + 20,100,10);
ctx.rotate(-angle*Math.PI/180);

Related

Rotate triangle around circle (2D)

I'm trying to rotate a triangle around a circle, the triangle should always face outwards, meaning it should rotate around the circle, AND around its center I'm guessing.
I found this question, which is something like what I need, but just in reverse.
Another thing I need is to have the triangle pointed at the user's mouse coords. aka the triangle is something like an arrow.
I just edited the code you linked and replaced the rectangle with a triangle, and animate() with a mouse move listener, of course:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var cx = 100;
var cy = 100;
var radious = 10;
var gap = 5;
var triangleHeight = 25;
var triangleBase = 10;
redraw(cx + 1, cy);
function redraw(mx, my)
{
mox = mx-cx;
moy = my-cy;
rotation = Math.atan2(moy, mox);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(cx, cy, radious, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
ctx.save();
ctx.translate(cx, cy);
ctx.rotate(rotation);
ctx.beginPath();
ctx.moveTo(radious+gap, -triangleBase/2);
ctx.lineTo(radious+gap, triangleBase/2);
ctx.lineTo(radious+gap+triangleHeight, 0);
ctx.lineTo(radious+gap, -triangleBase/2)
ctx.stroke();
ctx.restore();
}
canvas.addEventListener("mousemove", function (e) {
redraw(e.pageX, e.pageY);
}, false);
<canvas id="canvas"></canvas>
BTW, it's my very first piece of code in JS, so, feel free to correct my code if something is funny.

How do I rotate an object in canvas and js; my example is not rotating how I expect

I'm trying to rotate a rectangle about it's center but it's not rotating how I expect.
Here's an example:
https://jsfiddle.net/37ur8dfk/1/
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
let x = 100;
let y = 100;
let w = 100;
let h = 50;
// Draw a red dot to highlight the point I want to rotate the rectangle around
ctx.fillStyle = '#ff0000';
ctx.beginPath();
ctx.arc(x, y, 4, 0, 2 * Math.PI);
ctx.closePath();
ctx.fill();
// Attempt to rotate the rectangle aroumd x,y
ctx.save();
ctx.fillStyle = '#000000';
ctx.translate(-x, -y);
ctx.rotate(10 * Math.PI/180);
ctx.translate(x, y);
ctx.fillRect(x - w/2, y - h/2, w, h);
ctx.restore();
I have the center of the rectangle as x,y coords. I then translate it by -x,-y to change it's origin to 0,0. Then I rotate it by some degrees, but it does not seem to be rotating about the 0,0 coords. It's my understanding that rotate should rotate the entire context about the origin, or 0,0.
Please take a look at the jsfiddle to see what I mean.
What am I missing here?
You got it inversed.
You are not translating the rectangle, but the context's transformation matrix.
Think of this as a sheet of paper and an arm with pen.
When you translate your context, the arm is moving in the direction provided. When you rotate the context, the arm is rotating.
So to set your rectangle's center as the rotation origin you first need to move the arm so that the pen is in the center of the rectangle, then you'll be able to rotate. And we move back the arm to its initial position so that the x and y coords match.
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let x = 100;
let y = 100;
let w = 100;
let h = 50;
// Attempt to rotate the rectangle aroumd x,y
ctx.save();
ctx.fillStyle = '#000000';
// move to transformation-origin
ctx.translate(x, y);
// transform
ctx.rotate(10 * Math.PI/180);
// go back to where we were
ctx.translate(-x, -y);
ctx.fillRect(x - w/2, y - h/2, w, h);
ctx.restore();
// Draw a red dot to highlight the point I want to rotate the rectangle around
ctx.fillStyle = '#ff0000';
ctx.beginPath();
ctx.arc(x, y, 4, 0, 2 * Math.PI);
ctx.closePath();
ctx.fill();
<canvas id="canvas" width="500" height="400"></canvas>
Try (This will allow a rotation around the dot)
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
let x = 100;
let y = 100;
let w = 100;
let h = 50;
let angle = Math.PI/8;
ctx.save();
ctx.fillStyle = '#000000';
ctx.translate(x, y);
ctx.rotate(angle);
ctx.fillRect(0, 0, w, h);
ctx.restore();
ctx.save();
ctx.fillStyle = '#ff0000';
ctx.beginPath();
ctx.arc(x, y, 4, 0, 2 * Math.PI);
ctx.closePath();
ctx.fill();
ctx.restore();
canvas {
border: 1px solid black;
}
<canvas id="canvas" width="500" height="400"></canvas>

Prevent canvas element from manipulating others depending on order

I have been experimenting with canvas and things were going pretty well. However when it came time to rotate an object I had the hardest time getting it to rotate. When I finally did I found that depending on the order the objects being initiated it. The object with the rotation attributes would get passed on to objects being called after it.
All my objects were put into their own functions, and then called by a draw function. I am curious if this is always true and I have to be conscious of my objects order of initiation or if there is something I am missing.
Below if you move Obj1 and Obj2 before or after each other you will see the results are different. My goal is to have Obj1 before Obj2 and only have Obj1 rotated.
window.onload = function(){
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
x = 470,
y = 260;
canvas.width = 500;
canvas.height = 500;
function Obj1(){
ctx.beginPath();
ctx.translate(100,0);
ctx.rotate(20 * Math.PI / 180);
ctx.fillRect(x, y + 10, 20, 45);
ctx.fillStyle = 'blue';
ctx.fill();
ctx.closePath();
}
function Obj2(){
ctx.beginPath();
ctx.rect(0,300,100, 200);
ctx.fillStyle = "black";
ctx.fill();
ctx.closePath();
}
function draw(){
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
Obj1();
Obj2();
}
draw();
}
<canvas id="canvas"></canvas>
You need to reset the rotation matrix after rotating the object
Whats happening is that the transforms are cascading .
Rendering happens as a stack not a per element basis .
The order of operations is
TRANSFORM
DRAW
RESET
DRAW
This is also a recursive process .
You can say rotate the world scene / view port and also individual object .
TRANSFORM
TRANSFORM
DRAW
RESET
TRANSFORM
DRAW
RESET
RESET
If you post a simple code example I can review it for you
Have a look at
https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Transformations
function Obj1(){
ctx.save();
ctx.beginPath();
ctx.translate(100,0);
ctx.rotate(20 * Math.PI / 180);
ctx.fillRect(x, y + 10, 20, 45);
ctx.fillStyle = 'blue';
ctx.fill();
ctx.closePath();
ctx.restore();
}
I believe off the top of my head .

creating multiple clipping paths in HTML5 canvas using loop

I cannot create multiple clipping paths in canvas. With this code, if i=1, I get the clipping path working correctly. For i>1, I only see clipping if the paths are overlapping. Otherwise, nothing is drawn to the canvas.
function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
for (var i = 0; i < 5; i++) {
ctx.beginPath();
var x = 25 + 25 * i; // x coordinate
var y = 75; // y coordinate
var radius = 20; // Arc radius
var startAngle = 0; // Starting point on circle
var endAngle = Math.PI * 2; // End point on circle
var anticlockwise = true; // clockwise or anticlockwise
ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);
ctx.clip();
}
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, 800, 150);
}
If it is not possible to have multiple clipping masks on the canvas, is there another compositing method that is the same as clipping mask?
If you wish to have multiple shapes in your clip area you need to define all the shapes then apply the clip. If you set the clip after adding each shape you end up clipping only inside the previous clip.
So move ctx.clip() to after the for loop, it need only be called once, and move the ctx.beginPath() to before the loop.

Canvas polygons not touching properly

So I've been fiddling with the canvas element, and I seem to have run into a situation that is highly irritating, yet I haven't been able to find a solution.
Say that two polygons are drawn on a canvas, and that they should be touching each other. Where one polygon is drawn like this:
ctx.beginPath();
ctx.moveTo(oX,oY);
ctx.lineTo(oX=oX+k,oY=oY-h);
ctx.lineTo(oX=oX+k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY-h);
ctx.fill();
A simple version is implemented in this fiddle.
As you can probably see there is a thin line between these shapes. How can I avoid it? I have tried the solutions here, but they don't really seem to refer to this case, because I'm dealing with diagonal lines.
One solution
You could always use the stroke-line trick, but depending on your goal:
If it is to show many polygons next to each other, you could look at the polygons as simple squares.
Draw them in as such in an off-screen canvas next to each other. This will produce a result with no gaps.
Then transform the main canvas into the position you want those polygons to appear. Add rotation and/or skew depending on goal.
Finally, draw the off-screen canvas onto the main canvas as an image. Problem gone.
This will give you an accurate result with no extra steps in stroking, and the calculations for the boxes becomes very simple and fast to do (think 2d grid).
You have to use an off-screen canvas though. If you transform main canvas and draw in the shapes you will encounter the same problem as already present. This is because each point is transformed and if there is need for interpolation it will be calculated for each path shape separately. Drawing in an image will add interpolation on the whole surface, and only where there are gaps (non-opaque alpha). As we already are "gap-free" this is no longer a problem.
This will require an extra step in planning to place them correctly, but this is a simple step.
Example
Step 1 - draw boxes into an off-screen canvas:
This code draws on the off-screen canvas resulting in two boxes with no gap:
(the example uses an on-screen to show result, see next step for usage of off-screen canvas)
var ctx = document.querySelector("canvas").getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(10, 10, 50, 50);
ctx.fillRect(60, 10, 50, 50);
<canvas/>
Step 2 - transform main canvas and draw in off-screen canvas
When drawn into main canvas with transformation set, the result will be (pseudo-random transformation just to show):
var ctx = document.querySelector("canvas").getContext("2d");
// off-screen canvas
var octx = document.createElement("canvas").getContext("2d");
octx.fillStyle = "red";
octx.fillRect(10, 10, 50, 50);
octx.fillRect(60, 10, 50, 50);
// transform and draw to main
ctx.translate(80, 0);
ctx.rotate(0.5, Math.PI);
ctx.transform(1, 0, Math.tan(-0.5),1, 0,0); // skew
ctx.drawImage(octx.canvas, 0, 0);
<canvas />
Step 3 (optional) - Interaction
If you want to interact with the boxes you simply apply the same transform, then add path for a box and hit-test it against the mouse position. Redraw a single state, erase by clearing and draw back the off-screen canvas on top:
var ctx = document.querySelector("canvas").getContext("2d");
// off-screen canvas
var octx = document.createElement("canvas").getContext("2d");
octx.fillStyle = "red";
octx.fillRect(10, 10, 50, 50);
octx.fillRect(60, 10, 50, 50);
// allow us to reuse some of the steps:
function getTransforms() {
ctx.setTransform(1,0,0,1,0,0);
ctx.translate(80, 0);
ctx.rotate(0.5, Math.PI);
ctx.transform(1, 0, Math.tan(-0.5),1, 0,0); // skew
}
function clear() {
ctx.setTransform(1,0,0,1,0,0);
ctx.clearRect(0,0,300,150);
}
function redraw() {
ctx.drawImage(octx.canvas, 0, 0);
}
getTransforms();
redraw();
ctx.canvas.onmousemove = function(e) {
var r = this.getBoundingClientRect(),
x = e.clientX - r.left, y = e.clientY - r.top;
// box 1 (for many, use array)
ctx.beginPath();
ctx.rect(10, 10, 50, 50);
clear(); // these can be optimized to use state-flags
getTransforms(); // so they aren't redraw for every move...
redraw();
// just one box check here
if (ctx.isPointInPath(x, y)) {
ctx.fill();
}
};
<canvas />
Yes, it's annoying when filled polygons result in that tiny gap. It's especially common on diagonals that should theoretically meet.
A common workaround is to put a half-pixel, same-colored stroke around the polygons:
//Some basic setup ...
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var oX = 50;
var oY = 50;
var h = 33;
var k = 50;
ctx.fillStyle = 'red';
ctx.strokeStyle='red';
ctx.lineWidth=0.50;
//Draw one polygon
ctx.beginPath();
ctx.moveTo(oX,oY);
ctx.lineTo(oX=oX+k,oY=oY-h);
ctx.lineTo(oX=oX+k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY-h);
ctx.fill();
ctx.stroke();
//Draw another polygon
oX = oX+k;
oY = oY+h;
ctx.beginPath();
ctx.moveTo(oX,oY);
ctx.lineTo(oX=oX+k,oY=oY-h);
ctx.lineTo(oX=oX+k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY-h);
ctx.fill();
ctx.stroke();
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
//Some basic setup ...
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var oX = 50;
var oY = 50;
var h = 33;
var k = 50;
ctx.fillStyle = 'red';
ctx.strokeStyle='red';
ctx.lineWidth=0.50;
//Draw one polygon
ctx.beginPath();
ctx.moveTo(oX,oY);
ctx.lineTo(oX=oX+k,oY=oY-h);
ctx.lineTo(oX=oX+k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY-h);
ctx.fill();
ctx.stroke();
//Draw another polygon
oX = oX+k;
oY = oY+h;
ctx.beginPath();
ctx.moveTo(oX,oY);
ctx.lineTo(oX=oX+k,oY=oY-h);
ctx.lineTo(oX=oX+k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY-h);
ctx.fill();
ctx.stroke();
#canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>

Categories

Resources