+ 1

fillStyle, fillRect, issues.

<html> <head></head> <body> <canvas id="canvas1" width="400" height="300"> </canvas> <script> var c=document.getElementById("canvas1"); var ctx=c.getContext("2d"); ctx.fillStyle = "#FF0000"; ctx.fillRect(10,10, 100, 100); ctx.rotate( (Math.PI / 180) * 25); //rotate 25 degrees. ctx.fillStyle = "#0000FF"; ctx.fillRect(10,10, 100, 100); </script> </body> </html> If anyone can break down what is contained in the script element here, im having trouble understanding the functions of "ctx.rotate, ctx.fillRect, and ctx.fillStyle.

15th Feb 2019, 7:45 PM
Cory
Cory - avatar
5 odpowiedzi
+ 2
ctx.fillStyle sets the fill color of the thing you’re drawing. ctx.fillRect makes a rectangle and fills it (using the fill color), where the four values (10, 10, 100, 100) stand for x, y, width, and height respectively. ctx.rotate rotates the canvas, but only applies to things that are drawn AFTER it’s rotated. It takes one value. which is the rotation in radians, which is another unit for measuring angles. Math.PI is just π, and 2π radians = 360 degrees so π/180 radians is 1 degree.
16th Feb 2019, 1:35 AM
Rowsej
Rowsej - avatar
+ 2
ctx.rotate( (Math.PI / 180) * 90);
16th Feb 2019, 8:49 PM
Rowsej
Rowsej - avatar
+ 1
That all makes sense and certainly helps, but you lost me on the Math.PI part which was the main part i wasnt understanding. So Is the Math.PI required to rotate the canvas?
16th Feb 2019, 4:15 AM
Cory
Cory - avatar
+ 1
The rotate function is used to rotate the canvas, but only the stuff that’s drawn after the rotate command. It takes one value, which is the angle in radians (another unit of measurement for angles). 2pi is 360 deg, so pi / 180 (2pi / 360) is 1 deg. Math.PI in JavaScript is just pi, so (Math.PI / 180) * 25 is 25 deg. Hope that helps!
16th Feb 2019, 8:06 AM
Rowsej
Rowsej - avatar
+ 1
So say I wanted to rotate it 90 degrees. Since we must use radians what would that look like in the script. Feeling kinda dumb just cant wrap my head around the last part of it.
16th Feb 2019, 9:50 AM
Cory
Cory - avatar