i am having a problem rotating a ball that is bouncing around the screen when i put the rotate method in it just dissapears off the canvas in a very wide rotating arc.
It is working when the ball is static but when i put x,y velocity the problem starts.
Ant help someone can give me would be greatly appreciated.
Please see below the code i have so far.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Canvas</title>
<style type="text/css">
canvas {
border: 1px solid black;
}
body {
background-color: white;
}
</style>
</head>
<body>
<canvas id="canvas-for-ball"></canvas>
<script type="text/javascript">
// Gets a handle to the element with id canvasOne.
var canvas = document.getElementById("canvas-for-ball");
// Get a 2D context for the canvas.
var ctx = canvas.getContext("2d");
canvas.width = 500;
canvas.height = 500;
// The vertical location of the ball.
//var y = 10;
var yvel = 3;
var xvel = 3 ;
//ball object
var ball = {
x: 90,
y: 150,
r: 50
};
// A function to repeat every time the animation loops.
function repeatme() {
//clear canvas for each frame of the animation.
ctx.clearRect(0,0,500,500);
// Draw the ball (stroked, not filled).
//for loop to draw each line of th pie.
// i is set to 7. set i to whatever amount of sections you need.
for (var i = 0; i < 7; i++) {
//starting point
ctx.beginPath();
//move to positions the pen to the center of the ball
ctx.moveTo(ball.x, ball.y);
//circle craeted with x,y and r set. The final two arguments (Starting and ending point)
//change over each itteration of the loop giving a new point on the circle to draw to.
ctx.arc(ball.x, ball.y, ball.r, i*(2 * Math.PI / 7), (i+1)*(2 * Math.PI / 7));
//set line width
//set colour of the lines
ctx.strokeStyle = '#444';
//render the lines
ctx.stroke();
}
ctx.beginPath();
//the inner circle of the pizza
ctx.moveTo(ball.x, ball.y);
//ball.r is used - 10 pixles to put the smaller circle in the pizza.
ctx.arc(ball.x,ball.y,ball.r-10,0,2*Math.PI);
ctx.lineWidth = 2;
ctx.strokeStyle = '#444';
ctx.stroke();
ctx.translate(ball.x, ball.y);
// Rotate 1 degree
ctx.rotate(Math.PI / 180);
// Move registration point back to the top left corner of canvas
ctx.translate(-ball.x, -ball.y);
//draw the ball
//restore canvas back to original state
ctx.restore();
// Update the y location.
ball.y += yvel;
ball.x += xvel;
//put repeatme function into the animation frame and store it in animate
animate = window.requestAnimationFrame(repeatme);
//condition take into account the radius of the ball so
//it bounces at the edge of the canvas instead
//of going off of the screen to its center point.
if(ball.y >= canvas.height - ball.r){
//window.cancelAnimationFrame(animate);
yvel = yvel *-1;
}else if(ball.y <= ball.r){
yvel = yvel /-1;
}
if(ball.x >= canvas.width- ball.r){
xvel = xvel *-1;
}else if(ball.x <=ball.r){
xvel = xvel / -1;
}
}
// Get the animation going.
repeatme();
</script>
</body>
</html>
To rotate a rendered path. Set the origin to the point of rotation, rotate by the amount you want and render the path at 0,0
rotation += Math.PI / 180; // rotate 1 deg steps
ctx.lineWidth = 2;
ctx.strokeStyle = '#444';
ctx.setTransform(1, 0, 0, 1, ball.x, ball.y); // set the origin at the center
ctx.rotate(rotation); // set the rotation amount
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.arc(0, 0, ball.r - 10, 0, 2 * Math.PI);
ctx.stroke();
ctx.setTransform(1,0,0,1,0,0); // restore the default transform
Related
I am having some trouble drawing lines in circle with html5 canvas.
I am trying to make the bars look something like this
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
var bars = 50;
var radius = 100;
for(var i = 0; i < bars; i++){
var x = radius*Math.cos(i);
var y = radius*Math.sin(i);
draw_rectangle(x+200,y+200,1,13,i, ctx );
}
function draw_rectangle(x,y,w,h,deg, ctx){
ctx.save();
ctx.translate(x, y);
ctx.rotate(degrees_to_radians(deg));
ctx.fillStyle = "yellow";
ctx.fillRect(-1*(w/2), -1*(h/2), w, h);
ctx.restore();
}
function degrees_to_radians(degrees){
return degrees * Math.PI / 180;
}
function radians_to_degrees(radians){
return radians * 180 / Math.PI;
};
for some reason my lines are all crooked and unaligned. I really need help on this one. https://codepen.io/anon/pen/PRBdYV
The easiest way to deal with such a visualization is to play with the transformation matrix of your context.
You need to understand it as if you were holding a sheet of paper in your hands.
Instead of trying to draw the lines at the correct angle, rotate the sheet of paper, and always draw your lines in the same direction.
This way all you need in your drawing method is the angle, and the height of each bar.
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
// the position of the whole thing
var circleX = canvas.width / 2;
var circleY = canvas.height / 2;
//
var bars = 50;
var barWidth = 5;
// inner radius
var radius = 50;
ctx.fillStyle = "yellow";
// no need to use degrees, a full circle is just 2π
for(var i = 0; i < Math.PI*2; i+= (Math.PI*2 / bars)){
draw_rectangle(i, (Math.random()*30) + 10);
}
function draw_rectangle(rad, barHeight){
// reset and move to the center of our circle
ctx.setTransform(1,0,0,1, circleX, circleY);
// rotate the context so we face the correct angle
ctx.rotate(rad);
// move along y axis to reach the inner radius
ctx.translate(0, radius);
// draw the bar
ctx.fillRect(
-barWidth/2, // centered on x
0, // from the inner radius
barWidth,
barHeight // until its own height
);
}
canvas#canvas{
background:black;
}
<html>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
</body>
</html>
https://codepen.io/anon/pen/YajONR
Problems fixed: Math.cos wants radians, not degrees
We need to go from 0 to 360, so I adjusted the number of bars to make that a bit easier, and multiplied i by 6 (so the max value is 60*6==360)
If we don't add +90 when drawing the bars, we just get a circle
Check your codepen and figured out the problem lies in the degrees_to_radians
Here is the update link of you code.Link
PS I only looked at the shape of the circle not alignments of the bar :D
So I'm trying to have shapes animate across the canvas and then bounce back after hitting the edge, and I'm unclear why my other two shapes do not have velocity like my ball does. I'll post the code below.
<html>
<body>
<section>
<div>
<canvas id="canvas" width="700" height="300"></canvas>
</div>
<script type="text/javascript">
var canvas,
context,
x = Math.floor((Math.random() * 400) + 1), //Ball x coordinate
y = Math.floor((Math.random() * 300) + 1), //Ball y coordinate
dx = Math.floor((Math.random() * 10) + 1), //X velocity
dy = Math.floor((Math.random() * 4) + 1), //Y velocity
width = 700, //Width of the background
height = 300; //Height of the background
function drawCircle(x,y,r) { //Draws the ball
context.beginPath();
context.arc(x, y, r, 0, Math.PI*2, true);
context.fill();
}
function drawRect(x,y,w,h) { //Draws the background
context.beginPath();
context.rect(x,y,w,h);
context.closePath();
context.fill();
}
function start() { //Runs when the window loads. Stores canvas and context in variables. Runs "draw" on an interval of 10ms
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
return setInterval(draw, 10);
}
function drawSquare(){
var canvas = document.getElementById('canvas');
if (canvas.getContext){
var ctx = canvas.getContext('2d');
ctx.fillStyle = "white";
ctx.beginPath();
ctx.moveTo(200,50);
ctx.lineTo(250,50);
ctx.lineTo(300, 100);
ctx.lineTo(250,25);
ctx.fill();
}
}
function drawTri(){
var canvas = document.getElementById('canvas');
if (canvas.getContext){
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(75,50);
ctx.lineTo(100,75);
ctx.lineTo(75,25);
ctx.fill();
}
}
function draw() {
context.clearRect(0, 0, width, height); //Clears the drawing space
context.fillStyle = "black"; //Sets fillstyle to black (for the background)
drawRect(0,0, width, height); //Draws the background
context.fillStyle = "white"; //Sets fillstyle to white (for the ball)
drawCircle(x, y, 10);
drawTri();
drawSquare(); //Calls function to draw the ball
if (x + dx > width || x + dx < 0) //If the ball would leave the width (right or left) on the next redraw...
dx = -dx; //reverse the ball's velocity
if (y + dy > height || y + dy < 0) //If the ball would leave the height (top or bottom) on the next redraw...
dy = -dy; //reverse the ball's velocity
x += dx; //Increase ball x speed by velocity
y += dy; //Increase ball y speed by velocity
}
window.onload = start; //Run "start" function after the window loads
</script>
</section>
</body>
</html>
you forgot to do the drawing with the variables. And the variables are the same (as in the 2 shapes will always be together) because if x is 150 for the circle, the rect will be behind it. So, you need more variables to keep track of it like this: circ1x,circ1y,circ2x,circ2y,rect1x,rect1y,rect2x,rect2y
Your ball is being drawn using variable coordinates (x & y)
context.arc(x, y, r, 0, Math.PI*2, true);
Your shapes are being drawn using hardcoded, constant values:
ctx.moveTo(200,50);
ctx.lineTo(250,50);
ctx.lineTo(300, 100);
ctx.lineTo(250,25);
&
ctx.moveTo(75,50);
ctx.lineTo(100,75);
ctx.lineTo(75,25);
To animate them, use variables to draw the other shapes, and update those variables. eg.
var x = 75,
y = 50;
ctx.moveTo(x,y);
ctx.lineTo(x + 25, y + 25);
ctx.lineTo(x, y - 25);
I'm trying to animate polygons made using lineTo in canvas. It shows up, but won't move. I tried to follow the object approach, but it didn't seem to do anything.
Help?
<!doctype html>
<html>
<head>
<style>
canvas {
border: 1px solid black;
}
</style>
<script>
"use strict";
var canvas;
var ctx;
var timer;
var shapes;
var x;
var y;
function degreesToRadians(degrees) {
return (degrees*Math.PI)/180;
}
//to rotate stuff, not currently in use
function rotateStuff() {
roTimer = setInterval(ctx.rotate(degreesToRadians(60)),100);
}
//constructor for Shape object, not currently in use
function Shape() {
//this.x = canvas.width/2 + Math.random()*10-5;
//this.y = canvas.height/2 + Math.random()*10-5;
this.r = Math.random()*20-5;
this.vx = Math.random()*10-5;
this.vy = Math.random()*10-5;
var colors = ['red','green','orange','purple','blue','aqua','pink','gold'];
this.color = colors[Math.floor(Math.random()*colors.length)];
}
//pushes the shapes to an array, not currently in use
function makeShapes() {
shapes = [];
for (var i = 0; i<2; i++){
shapes.push(new Shape());
}
}
//fills and resets background
function fillBackground() {
ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = 'rgba(0,0,0,0.3)';
ctx.fillRect(0,0,canvas.width,canvas.height);
ctx.globalCompositeOperation = 'lighter';
}
//draws the shape
function drawShapes(r, p, m) {
//canvas, x position, y position, radius, number of points, fraction of radius for inset
fillBackground();
x = 350;
y = 350;
r = Math.random()*20-5;
//for (var i = 0; i < shapes.length; i++) {
//var s = shapes[i];
ctx.save();
ctx.beginPath();
ctx.translate(x, y);
ctx.moveTo(0,0-r);
//}
for (var i2 = 0; i2 < p; i2++) {
ctx.rotate(Math.PI / p);
ctx.lineTo(0, 0 - (r*m));
ctx.rotate(Math.PI / p);
ctx.lineTo(0, 0 - r);
}
ctx.fillStyle = "yellow";
ctx.fill();
var vx = Math.random()*10-5;
var vy = Math.random()*10-5;
x += vx;
y += vy;
r -=8
ctx.restore();
}
//}
window.onload = function() {
canvas = document.getElementById('animCanvas');
ctx = canvas.getContext('2d');
//makeShapes();
//console.log(shapes);
timer = setInterval(drawShapes(40, 5, 0.5), 100);
//timer2 = setInterval(makeShapes, 4500);
}
</script>
</head>
<body>
<canvas width='700' height='700' id='animCanvas'></canvas>
</body>
</html>
A coding hint: Separate your code into discrete duties. This separation lets you concentrate your coding focus on simpler tasks. And once you've got that task running correctly you can move onto another task without worrying that a previous task has become broken.
Here are the tasks for your "rotate stars" project
1. Draw a star and
2. Rotate that star using animation.*
... and their descriptions
drawShapes() draws one star at a specified [x,y] position at a specified currentAngle
animate() runs an animation loop that:
Clears the canvas.
Fills the background.
Draws the star (or many stars) with `drawShapes`.
Changes the `currentAngle` rotation for the next loop.
Requests another animation loop.
About rotating
Rotating your shape is a simple 2 step process:
1. Move to the shape's centerpoint: `.translate(centerX,centerY)'
2. Rotate the canvas to the currently desired angle: `rotate(currentAngle)`
Since translate and rotate are not automatically undone, you must "clean up" after your transformations. An easy way to do that is to do this: context.setTransform(1,0,0,1,0,0). This sets the internal transformation matrix to its default state (==fully untransformed).
So your rotation process becomes:
1. Move to the shape's centerpoint: `.translate(centerX,centerY)'
2. Rotate the canvas to the currently desired angle: `.rotate(currentAngle)`
3. Reset the canvas: `.setTransform(1,0,0,1,0,0)`
Here's annotated code and a Demo:
var canvas;
var ctx;
canvas = document.getElementById('animCanvas');
ctx = canvas.getContext('2d');
var cw=canvas.width;
var ch=canvas.height;
var shapes=[];
var star1={ x:50, y:100, r:40, currentAngle:0, p:5, m:.5, fill:'yellow',angleChange:Math.PI/60}
var star2={ x:150, y:100, r:25, currentAngle:0, p:55, m:5, fill:'blue',angleChange:-Math.PI/360}
var star3={ x:250, y:100, r:25, currentAngle:0, p:15, m:3, fill:'red',angleChange:Math.PI/120}
requestAnimationFrame(animate);
function drawShapes(star) {
ctx.save();
// translate to the star's centerpoint
ctx.translate(star.x,star.y);
// rotate to the current angle
ctx.rotate(star.currentAngle)
// draw the star
ctx.beginPath();
ctx.moveTo(0,0-star.r);
for (var i2 = 0; i2 < star.p; i2++) {
ctx.rotate(Math.PI / star.p);
ctx.lineTo(0, 0 - (star.r*star.m));
ctx.rotate(Math.PI / star.p);
ctx.lineTo(0, 0 - star.r);
}
ctx.fillStyle =star.fill;
ctx.fill();
ctx.restore();
}
function fillBackground() {
ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = 'rgba(0,0,0,0.3)';
ctx.fillRect(0,0,canvas.width,canvas.height);
ctx.globalCompositeOperation = 'lighter';
}
function animate(time){
// clear the canvas
ctx.clearRect(0,0,cw,ch);
// fill the background
fillBackground();
// draw the stars
// If you put star1,star2,star3 in a stars[] array then
// you could simply the following demo code by looping
// through the array
//
// draw the star1
drawShapes(star1);
// increase star1's current rotation angle
star1.currentAngle+=star1.angleChange;
// draw the star2
drawShapes(star2);
// increase star2's current rotation angle
star2.currentAngle+=star2.angleChange;
// draw the star3
drawShapes(star3);
// increase star3's current rotation angle
star3.currentAngle+=star2.angleChange;
// request another animation loop
requestAnimationFrame(animate);
}
<canvas width='700' height='700' id='animCanvas'></canvas> </body>
I have built a canvas project with https://github.com/petalvlad/angular-canvas-ext
<canvas width="640" height="480" ng-show="activeateCanvas" ap-canvas src="src" image="image" zoomable="true" frame="frame" scale="scale" offset="offset"></canvas>
I am successfully able to zoom and pan the image using following code
scope.zoomIn = function() {
scope.scale *= 1.2;
}
scope.zoomOut = function() {
scope.scale /= 1.2;
}
Additionally I want to rotate the image. any help i can get with which library i can use and how can i do it inside angularjs.
You can rotate an image using context.rotate function in JavaScript.
Here is an example of how to do this:
var canvas = null;
var ctx = null;
var angleInDegrees = 0;
var image;
var timerid;
function imageLoaded() {
image = document.createElement("img");
canvas = document.getElementById("canvas");
ctx = canvas.getContext('2d');
image.onload = function() {
ctx.drawImage(image, canvas.width / 2 - image.width / 2, canvas.height / 2 - image.height / 2);
};
image.src = "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcT7vR66BWT_HdVJpwxGJoGBJl5HYfiSKDrsYrzw7kqf2yP6sNyJtHdaAQ";
}
function drawRotated(degrees) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.translate(canvas.width / 2, canvas.height / 2);
ctx.rotate(degrees * Math.PI / 180);
ctx.drawImage(image, -image.width / 2, -image.height / 2);
ctx.restore();
}
<button onclick="imageLoaded();">Load Image</button>
<div>
<canvas id="canvas" width=360 height=360></canvas><br>
<button onclick="javascript:clearInterval(timerid);
timerid = setInterval(function() {
angleInDegrees += 2;
drawRotated(angleInDegrees);
}, 100);">
Rotate Left
</button>
<button onclick="javascript:clearInterval(timerid);
timerid = setInterval(function() {
angleInDegrees -= 2;
drawRotated(angleInDegrees);
}, 100);">
Rotate Right
</button>
</div>
With curtesy to this page!
Once you can get your hands on the canvas context:
// save the context's co-ordinate system before
// we screw with it
context.save();
// move the origin to 50, 35 (for example)
context.translate(50, 35);
// now move across and down half the
// width and height of the image (which is 128 x 128)
context.translate(64, 64);
// rotate around this point
context.rotate(0.5);
// then draw the image back and up
context.drawImage(logoImage, -64, -64);
// and restore the co-ordinate system to its default
// top left origin with no rotation
context.restore();
To do it in a single state change. The ctx transformation matrix has 6 parts. ctx.setTransform(a,b,c,d,e,f); (a,b) represent the x,y direction and scale the top of the image will be drawn along. (c,d) represent the x,y direction and scale the side of the image will be drawn along. (e,f) represent the x,y location the image will be draw.
The default matrix (identity matrix) is ctx.setTransform(1,0,0,1,0,0) draw the top in the direction (1,0) draw the side in the direction (0,1) and draw everything at x = 0, y = 0.
Reducing state changes improves the rendering speed. When its just a few images that are draw then it does not matter that much, but if you want to draw 1000+ images at 60 frames a second for a game you need to minimise state changes. You should also avoid using save and restore if you can.
The function draws an image rotated and scaled around its center point that will be at x,y. Scale less than 1 makes the images smaller, greater than one makes it bigger. ang is in radians with 0 having no rotation, Math.PI is 180deg and Math.PI*0.5 Math.PI*1.5 are 90 and 270deg respectively.
function drawImage(ctx, img, x, y, scale, ang){
var vx = Math.cos(ang) * scale; // create the vector along the image top
var vy = Math.sin(ang) * scale; //
// this provides us with a,b,c,d parts of the transform
// a = vx, b = vy, c = -vy, and d = vx.
// The vector (c,d) is perpendicular (90deg) to (a,b)
// now work out e and f
var imH = -(img.Height / 2); // get half the image height and width
var imW = -(img.Width / 2);
x += imW * vx + imH * -vy; // add the rotated offset by mutliplying
y += imW * vy + imH * vx; // width by the top vector (vx,vy) and height by
// the side vector (-vy,vx)
// set the transform
ctx.setTransform(vx, vy, -vy, vx, x, y);
// draw the image.
ctx.drawImage(img, 0, 0);
// if needed to restore the ctx state to default but should only
// do this if you don't repeatably call this function.
ctx.setTransform(1, 0, 0, 1, 0, 0); // restores the ctx state back to default
}
What I have is this:
What I want is to rotate the red rectangle e.g. 20 degrees, but this is what I end up with:
As you can see, the rectangle is rotated perfectly, but it's moved and doesn't match the black object anymore.
My code is:
context.save();
context.rotate(angle * Math.PI / 180); // in the screenshot I used angle = 20
context.translate(angle * 4, 2);
context.fillStyle = "red";
context.fillRect(x + 14, y - 16, 5, 16);
context.restore();
I want to make the rectangle turn without moving from its position.
Thanks.
Sounds like you want to rotate the rect around its centerpoint.
Red rectangle is original, Yellow rectangle is rotated around the centerpoint.
To do that you need to first context.translate to the rect's centerpoint before rotating.
// move the rotation point to the center of the rect
ctx.translate( x+width/2, y+height/2 );
// rotate the rect
ctx.rotate(degrees*Math.PI/180);
Note that the context is now in its rotated state.
That means drawing position [0,0] is visually at [ x+width/2, y+height/2 ].
So you must draw the rotated rect at [ -width/2, -height/2 ] (not at the original unrotated x/y).
// draw the rect on the transformed context
// Note: after transforming [0,0] is visually [-width/2, -height/2]
// so the rect needs to be offset accordingly when drawn
ctx.rect( -width/2, -height/2, width,height);
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/z4p3n/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var startX=50;
var startY=80;
// draw an unrotated reference rect
ctx.beginPath();
ctx.rect(startX,startY,100,20);
ctx.fillStyle="blue";
ctx.fill();
// draw a rotated rect
drawRotatedRect(startX,startY,100,20,45);
function drawRotatedRect(x,y,width,height,degrees){
// first save the untranslated/unrotated context
ctx.save();
ctx.beginPath();
// move the rotation point to the center of the rect
ctx.translate( x+width/2, y+height/2 );
// rotate the rect
ctx.rotate(degrees*Math.PI/180);
// draw the rect on the transformed context
// Note: after transforming [0,0] is visually [x,y]
// so the rect needs to be offset accordingly when drawn
ctx.rect( -width/2, -height/2, width,height);
ctx.fillStyle="gold";
ctx.fill();
// restore the context to its untranslated/unrotated state
ctx.restore();
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
You can use a simple function to do this as an alternative to translate and rotate:
This function will let you draw a line starting at x and y, and end at length at angle:
function lineToAngle(ctx, x1, y1, length, angle) {
angle *= Math.PI / 180;
var x2 = x1 + length * Math.cos(angle),
y2 = y1 + length * Math.sin(angle);
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
return {x: x2, y: y2};
}
Usage:
lineToAngle(ctx, x, y, length, angle);
Demo
var canvas = document.querySelector('canvas'),
ctx = canvas.getContext('2d'),
x = 100, y =50, length = 40, angle = 0, dlt = -2;
(function animate() {
//clear
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
lineToAngle(ctx, x, y, length, angle);
ctx.lineWidth = 10;
ctx.stroke();
angle += dlt;
if (angle < -90 || angle > 0) dlt = -dlt;
requestAnimationFrame(animate);
})();
function lineToAngle(ctx, x1, y1, length, angle) {
angle *= Math.PI / 180;
var x2 = x1 + length * Math.cos(angle),
y2 = y1 + length * Math.sin(angle);
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
return {x: x2, y: y2};
}
body {background-color:#555557}
canvas {background:#ddd;border:1px solid #000}
<canvas></canvas>
In the specific case of a rectangle, you can just draw a line.
In HTML5 canvas, lines are drawn exactly like rectangles, as such, you can use this function:
let canvas = document.getElementById('myCanvas')
let ctx = canvas.getContext('2d')
function drawRotatedRect(ctx, x, y, width, height, angle) {
angle *= Math.PI / 180
ctx.lineWidth = height / 2
ctx.beginPath()
ctx.moveTo(x, y)
ctx.lineTo(x + width * Math.cos(angle), y + width * Math.sin(angle))
ctx.stroke()
}
drawRotatedRect(ctx, 30, 30, 200, 100, 20)
canvas {
border: 1px solid black;
width: 100%;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Rotated Rectangle</title>
</head>
<body>
<canvas id='myCanvas'></canvas>
</body>
</html>