I have already looked for many questions like this and his answers on stackoverflow but it seems that I never complety have the exact same problem:
Player, created at x = canvas.width /2, y = canvas.height /2
The code that I use to generate the various sprites on the canvas is:
class Sprite {
constructor({
position,
imageSrc,
scale,
framesMax = 1,
offset = { x: 0, y: 0 },
}) {
this.position = position
this.width = 50
this.height = 150
this.image = new Image()
this.image.src = imageSrc
this.scale = scale
this.framesMax = framesMax
this.framesCurrent = 0
this.framesElapsed = 0
this.framesHold = 5
this.offset = offset
}
draw() {
c.drawImage(
this.image,
this.framesCurrent * (this.image.width / this.framesMax),
0,
this.image.width / this.framesMax,
this.image.height,
this.position.x - this.offset.x,
this.position.y - this.offset.y,
(this.image.width / this.framesMax) * this.scale,
this.image.height * this.scale
)
}
animateFrames() {
this.framesElapsed++
if (this.framesElapsed % this.framesHold === 0) {
if (this.framesCurrent < this.framesMax - 1) {
this.framesCurrent++
} else {
this.framesCurrent = 0
}
}
}
update() {
this.draw()
this.animateFrames()
}
}
Then what I want to do is to create the "Fishnet" that you see in the first picture, and position the image on a certain angle, but keep the starting point of the coordinates, another image is possible useful.
Fishnet:
I have tried many things, but the most common that I see everywhere, is to draw de image, save the canvas context, translate the canvas, rotate the canvas, and draw the image.
For reasons that I can't get in to, I never could rotate the image and maintain the starting position.
I wrote another sprite class specific for this rotation, and added the rotate method:
rotate(){
c.save();
c.translate(x,y)
c.rotate(this.angle)
c.drawImage(
this.image,
-(this.image.width),
-(this.image.height),
150,
50,
this.position.x - this.offset.x,
this.position.y - this.offset.y,
(this.image.width / this.framesMax) * this.scale,
this.image.height * this.scale
)
c.restore();
}
The x and y continue to be the (canvas.width / 2) and (canvas.height / 2) in witch I have my doubts of working...
The angle is calculate by the position of the yellow (projetile) and the center of the canvas:
angle = Math.atan2(projectile.position.y - canvas.height / 2, projectile.position.x - canvas.width / 2)
One of the few attempts this has """worked""", was by an example that I saw online, but I had to remove most of my parameters on the drawImage as I rotated it, like this:
draw() {
c.drawImage(
this.image,
this.framesCurrent * (this.image.width / this.framesMax),
0,
this.image.width / this.framesMax,
this.image.height,
this.position.x - this.offset.x,
this.position.y - this.offset.y,
(this.image.width / this.framesMax) * this.scale,
this.image.height * this.scale
)
}
Rotate:
rotate(){
c.save();
c.translate(x,y)
c.rotate(this.angle)
c.drawImage(
this.image,
-(this.image.width),
-(this.image.height)
)
c.restore();
Then I called the Draw method and after the Rotate method. It generated me 2 images. If I only call the rotate method it is obvious that I create only one image, but idk why, can't get the drawImage from rotate to work with the scale and position's x,y. Only works with those 3 paramaters
(this.image, -(this.image.width),-(this.image.height))
Here is the result of working only with the rotate method:
Rotation working with no scaling or proper angle (maybe translate is wrong?)
It can be a problem only on the angle, and I will try to figure it out (I do not think so anyway, because I have another solution launching a circle at that angle to check if its right, and it is.)
Still can't get it to work with scaling.. like I do in the draw() method above.
I know this will be very confusing but I have little knowledge of canvas in JavaScript (and overall..), feel free to comment on more information.
Thanks in advance.
Expanding on my comment, you can just draw the net yourself no need for an image, it does not look too complicated, an arc and a few lines should be a good starting point to test the concept
And the most complicated part I see you are already using:
c.translate(x,y)
c.rotate(angle)
Here is a quick example:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var angle = 0
function drawNet(x, y, w, h, angle) {
ctx.beginPath();
ctx.translate(x,y)
ctx.rotate(angle)
ctx.moveTo(0, 0);
ctx.arc(0, h, w / 2, 0, Math.PI)
ctx.lineTo(0, 0);
ctx.stroke();
ctx.rotate(-angle)
ctx.translate(-x,-y)
}
function draw() {
ctx.clearRect(0,0, c.width, c.height)
drawNet(70, 50, 55, 50, angle)
drawNet(200, 80 + Math.sin(angle)*30, 45, 30, -angle*2)
angle += 0.1
}
setInterval(draw, 60)
<canvas id="myCanvas" style="border:1px solid;">
In my function drawNet I'm translating and rotating to the given parameters then rotating back and translating back to the original position, that allows all following drawing to be at the correct location
I am working on a Canvas Game on HTML5 Canvas with Vanilla JS.
For some reason I am noticing that when I set the player sprite to be drawn in at on the x-axis at x=0, the player appears indented to the right.
(this appears to be disrupting my collision detection)
I have the same issue with other sprites I have generated with the piskel app. Another sprite I used from another creator didn't have this issue.
Does anyone have any suggestions?
Here is a link to my game: http://zcbuhler.github.io/spaceDrift
The player should be at 0 on the x-axis for the starting point, but as you can see appears to be tabbed over.
General purpose sprite rendering
I render sprites with the following function.
// assumes ctx is scoped and is the rendering 2d context
function drawSprite(img, x, y, scale, rotate, alpha){
var w = img.width;
var h = img.height;
ctx.setTransform(scale, 0, 0 ,scale, x, y);
ctx.rotate(rotate);
ctx.globalAlpha = alpha;
ctx.drawImage(img, 0, 0, w, h, -w/2,-h/2, w, h);
}
It draws the sprite with its center at x,y. It is scaled and and rotated and its alpha is set. On a average laptop and on firefox it can do 2000+ sprites in realtime. On chrome its about 1000+
To set the center point use
// assumes ctx is scoped and is the rendering 2d context
function drawSpriteCenter(img, x, y, cx, cy, scale, rotate, alpha){
var w = img.width;
var h = img.height;
ctx.setTransform(scale, 0, 0 ,scale, x, y);
ctx.rotate(rotate);
ctx.globalAlpha = alpha;
ctx.drawImage(img, 0, 0, w, h, -cx,-cy, w, h);
}
where cx, and cy s the center point of the sprite. (the point around which it rotates)
To draw a sprite with a center cx,cy at x,y and a scale for x and y, rotated with alpha.
// assumes ctx is scoped and is the rendering 2d context
function drawSpriteFull(img, x, y, cx, cy, scaleX, scaleY, rotate, alpha){
var w = img.width;
var h = img.height;
ctx.setTransform(scaleX, 0, 0 ,scaleY, x, y);
ctx.rotate(rotate);
ctx.globalAlpha = alpha;
ctx.drawImage(img, 0, 0, w, h, -cx, -cy, w, h);
}
The functions modify the current transform and alpha. To reset the canvas state once you are done rendering the sprites you can use
function resetCtx(){
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.globalAlpha = 1;
}
You should be able to correct the player's position like #Bangkokian pointed out.
Simply wrap that in a function like so:
function positionPlayer(x, y) {
player.pos = [x -= (player.w / 2), y];
}
or even make that a method of the players object.
The collision detection could be solved similarly by altering the 'checkCollision' function to something like:
var checkCollision = function(rect1, rect2) {
// debugger
// centers
var rect1CenteredPos = [rect1.pos[0] - (rect1.w / 2), rect1.pos[1] - (rect1.h / 2)];
var rect2CenteredPos = [rect2.pos[0] - (rect2.w / 2), rect2.pos[1] - (rect2.h / 2)];
// console.log(bulletsArray.length);
if (rect1CenteredPos[0] < rect2CenteredPos[0] + rect2.w &&
rect1CenteredPos[0] + rect1.w > rect2CenteredPos[0] &&
rect1CenteredPos[1] < rect2CenteredPos[1] + rect2.h &&
rect1.h + rect1CenteredPos[1] > rect2CenteredPos[1]) {
return true;
}
return false;
}
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);
There doesnt seem to be a native function to draw an oval-like shape. Also i am not looking for the egg-shape.
Is it possible to draw an oval with 2 bezier curves?
Somebody expierenced with that?
My purpose is to draw some eyes and actually im just using arcs.
Thanks in advance.
Solution
So scale() changes the scaling for all next shapes.
Save() saves the settings before and restore is used to restore the settings to draw new shapes without scaling.
Thanks to Jani
ctx.save();
ctx.scale(0.75, 1);
ctx.beginPath();
ctx.arc(20, 21, 10, 0, Math.PI*2, false);
ctx.stroke();
ctx.closePath();
ctx.restore();
updates:
scaling method can affect stroke width appearance
scaling method done right can keep stroke width intact
canvas has ellipse method that Chrome now supports
added updated tests to JSBin
JSBin Testing Example (updated to test other's answers for comparison)
Bezier - draw based on top left containing rect and width/height
Bezier with Center - draw based on center and width/height
Arcs and Scaling - draw based on drawing circle and scaling
see Deven Kalra's answer
Quadratic Curves - draw with quadratics
test appears to not draw quite the same, may be implementation
see oyophant's answer
Canvas Ellipse - using W3C standard ellipse() method
test appears to not draw quite the same, may be implementation
see Loktar's answer
Original:
If you want a symmetrical oval you could always create a circle of radius width, and then scale it to the height you want (edit: notice this will affect stroke width appearance - see acdameli's answer), but if you want full control of the ellipse here's one way using bezier curves.
<canvas id="thecanvas" width="400" height="400"></canvas>
<script>
var canvas = document.getElementById('thecanvas');
if(canvas.getContext)
{
var ctx = canvas.getContext('2d');
drawEllipse(ctx, 10, 10, 100, 60);
drawEllipseByCenter(ctx, 60,40,20,10);
}
function drawEllipseByCenter(ctx, cx, cy, w, h) {
drawEllipse(ctx, cx - w/2.0, cy - h/2.0, w, h);
}
function drawEllipse(ctx, x, y, w, h) {
var kappa = .5522848,
ox = (w / 2) * kappa, // control point offset horizontal
oy = (h / 2) * kappa, // control point offset vertical
xe = x + w, // x-end
ye = y + h, // y-end
xm = x + w / 2, // x-middle
ym = y + h / 2; // y-middle
ctx.beginPath();
ctx.moveTo(x, ym);
ctx.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
ctx.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
ctx.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
ctx.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
//ctx.closePath(); // not used correctly, see comments (use to close off open path)
ctx.stroke();
}
</script>
Here is a simplified version of solutions elsewhere. I draw a canonical circle, translate and scale and then stroke.
function ellipse(context, cx, cy, rx, ry){
context.save(); // save state
context.beginPath();
context.translate(cx-rx, cy-ry);
context.scale(rx, ry);
context.arc(1, 1, 1, 0, 2 * Math.PI, false);
context.restore(); // restore to original state
context.stroke();
}
There is now a native ellipse function for canvas, very similar to the arc function although now we have two radius values and a rotation which is awesome.
ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise)
Live Demo
ctx.ellipse(100, 100, 10, 15, 0, 0, Math.PI*2);
ctx.fill();
Only seems to work in Chrome currently
The bezier curve approach is great for simple ovals. For more control, you can use a loop to draw an ellipse with different values for the x and y radius (radiuses, radii?).
Adding a rotationAngle parameter allows the oval to be rotated around its center by any angle. Partial ovals can be drawn by changing the range (var i) over which the loop runs.
Rendering the oval this way allows you to determine the exact x,y location of all points on the line. This is useful if the postion of other objects depend on the location and orientation of the oval.
Here is an example of the code:
for (var i = 0 * Math.PI; i < 2 * Math.PI; i += 0.01 ) {
xPos = centerX - (radiusX * Math.sin(i)) * Math.sin(rotationAngle * Math.PI) + (radiusY * Math.cos(i)) * Math.cos(rotationAngle * Math.PI);
yPos = centerY + (radiusY * Math.cos(i)) * Math.sin(rotationAngle * Math.PI) + (radiusX * Math.sin(i)) * Math.cos(rotationAngle * Math.PI);
if (i == 0) {
cxt.moveTo(xPos, yPos);
} else {
cxt.lineTo(xPos, yPos);
}
}
See an interactive example here: http://www.scienceprimer.com/draw-oval-html5-canvas
You could also try using non-uniform scaling. You can provide X and Y scaling, so simply set X or Y scaling larger than the other, and draw a circle, and you have an ellipse.
You need 4 bezier curves (and a magic number) to reliably reproduce an ellipse. See here:
www.tinaja.com/glib/ellipse4.pdf
Two beziers don't accurately reproduce an ellipse. To prove this, try some of the 2 bezier solutions above with equal height and width - they should ideally approximate a circle but they won't. They'll still look oval which goes to prove they aren't doing what they are supposed to.
Here's something that should work:
http://jsfiddle.net/BsPsj/
Here's the code:
function ellipse(cx, cy, w, h){
var ctx = canvas.getContext('2d');
ctx.beginPath();
var lx = cx - w/2,
rx = cx + w/2,
ty = cy - h/2,
by = cy + h/2;
var magic = 0.551784;
var xmagic = magic*w/2;
var ymagic = h*magic/2;
ctx.moveTo(cx,ty);
ctx.bezierCurveTo(cx+xmagic,ty,rx,cy-ymagic,rx,cy);
ctx.bezierCurveTo(rx,cy+ymagic,cx+xmagic,by,cx,by);
ctx.bezierCurveTo(cx-xmagic,by,lx,cy+ymagic,lx,cy);
ctx.bezierCurveTo(lx,cy-ymagic,cx-xmagic,ty,cx,ty);
ctx.stroke();
}
I did a little adaptation of this code (partially presented by Andrew Staroscik) for peoplo who do not want a so general ellipse and who have only the greater semi-axis and the excentricity data of the ellipse (good for astronomical javascript toys to plot orbits, for instance).
Here you go, remembering that one can adapt the steps in i to have a greater precision in the drawing:
/* draw ellipse
* x0,y0 = center of the ellipse
* a = greater semi-axis
* exc = ellipse excentricity (exc = 0 for circle, 0 < exc < 1 for ellipse, exc > 1 for hyperbole)
*/
function drawEllipse(ctx, x0, y0, a, exc, lineWidth, color)
{
x0 += a * exc;
var r = a * (1 - exc*exc)/(1 + exc),
x = x0 + r,
y = y0;
ctx.beginPath();
ctx.moveTo(x, y);
var i = 0.01 * Math.PI;
var twoPi = 2 * Math.PI;
while (i < twoPi) {
r = a * (1 - exc*exc)/(1 + exc * Math.cos(i));
x = x0 + r * Math.cos(i);
y = y0 + r * Math.sin(i);
ctx.lineTo(x, y);
i += 0.01;
}
ctx.lineWidth = lineWidth;
ctx.strokeStyle = color;
ctx.closePath();
ctx.stroke();
}
My solution is a bit different than all of these. Closest I think is the most voted answer above though, but I think this way is a bit cleaner and easier to comprehend.
http://jsfiddle.net/jaredwilli/CZeEG/4/
function bezierCurve(centerX, centerY, width, height) {
con.beginPath();
con.moveTo(centerX, centerY - height / 2);
con.bezierCurveTo(
centerX + width / 2, centerY - height / 2,
centerX + width / 2, centerY + height / 2,
centerX, centerY + height / 2
);
con.bezierCurveTo(
centerX - width / 2, centerY + height / 2,
centerX - width / 2, centerY - height / 2,
centerX, centerY - height / 2
);
con.fillStyle = 'white';
con.fill();
con.closePath();
}
And then use it like this:
bezierCurve(x + 60, y + 75, 80, 130);
There are a couple use examples in the fiddle, along with a failed attempt to make one using quadraticCurveTo.
I like the Bezier curves solution above. I noticed the scale also affects the line width so if you're trying to draw an ellipse that is wider than it is tall, your top and bottom "sides" will appear thinner than your left and right "sides"...
a good example would be:
ctx.lineWidth = 4;
ctx.scale(1, 0.5);
ctx.beginPath();
ctx.arc(20, 20, 10, 0, Math.PI * 2, false);
ctx.stroke();
you should notice the width of the line at the peak and valley of the ellipse are half as wide as at the left and right apexes (apices?).
Chrome and Opera support ellipse method for canvas 2d context, but IE,Edge,Firefox and Safari don't support it.
We can implement the ellipse method by JS or use a third-party polyfill.
ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise)
Usage example:
ctx.ellipse(20, 21, 10, 10, 0, 0, Math.PI*2, true);
You can use a canvas-5-polyfill to provide ellipse method.
Or just paste some js code to provide ellipse method:
if (CanvasRenderingContext2D.prototype.ellipse == undefined) {
CanvasRenderingContext2D.prototype.ellipse = function(x, y, radiusX, radiusY,
rotation, startAngle, endAngle, antiClockwise) {
this.save();
this.translate(x, y);
this.rotate(rotation);
this.scale(radiusX, radiusY);
this.arc(0, 0, 1, startAngle, endAngle, antiClockwise);
this.restore();
}
}
Yes, it is possible with two bezier curves - here's a brief tutorial/example:
http://www.williammalone.com/briefs/how-to-draw-ellipse-html5-canvas/
Since nobody came up with an approach using the simpler quadraticCurveTo I am adding a solution for that. Simply replace the bezierCurveTo calls in the #Steve's answer with this:
ctx.quadraticCurveTo(x,y,xm,y);
ctx.quadraticCurveTo(xe,y,xe,ym);
ctx.quadraticCurveTo(xe,ye,xm,ye);
ctx.quadraticCurveTo(x,ye,x,ym);
You may also remove the closePath. The oval is looking slightly different though.
This is another way of creating an ellipse like shape, although it uses the "fillRect()" function this can be used be changing the arguments in the fillRect() function.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Sine and cosine functions</title>
</head>
<body>
<canvas id="trigCan" width="400" height="400"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("trigCan"), ctx = canvas.getContext('2d');
for (var i = 0; i < 360; i++) {
var x = Math.sin(i), y = Math.cos(i);
ctx.stroke();
ctx.fillRect(50 * 2 * x * 2 / 5 + 200, 40 * 2 * y / 4 + 200, 10, 10, true);
}
</script>
</body>
</html>
With this you can even draw segments of an ellipse:
function ellipse(color, lineWidth, x, y, stretchX, stretchY, startAngle, endAngle) {
for (var angle = startAngle; angle < endAngle; angle += Math.PI / 180) {
ctx.beginPath()
ctx.moveTo(x, y)
ctx.lineTo(x + Math.cos(angle) * stretchX, y + Math.sin(angle) * stretchY)
ctx.lineWidth = lineWidth
ctx.strokeStyle = color
ctx.stroke()
ctx.closePath()
}
}
http://jsfiddle.net/FazAe/1/
Here's a function I wrote that uses the same values as the ellipse arc in SVG. X1 & Y1 are the last coordinates, X2 & Y2 are the end coordinates, radius is a number value and clockwise is a boolean value. It also assumes your canvas context has already been defined.
function ellipse(x1, y1, x2, y2, radius, clockwise) {
var cBx = (x1 + x2) / 2; //get point between xy1 and xy2
var cBy = (y1 + y2) / 2;
var aB = Math.atan2(y1 - y2, x1 - x2); //get angle to bulge point in radians
if (clockwise) { aB += (90 * (Math.PI / 180)); }
else { aB -= (90 * (Math.PI / 180)); }
var op_side = Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2)) / 2;
var adj_side = Math.sqrt(Math.pow(radius, 2) - Math.pow(op_side, 2));
if (isNaN(adj_side)) {
adj_side = Math.sqrt(Math.pow(op_side, 2) - Math.pow(radius, 2));
}
var Cx = cBx + (adj_side * Math.cos(aB));
var Cy = cBy + (adj_side * Math.sin(aB));
var startA = Math.atan2(y1 - Cy, x1 - Cx); //get start/end angles in radians
var endA = Math.atan2(y2 - Cy, x2 - Cx);
var mid = (startA + endA) / 2;
var Mx = Cx + (radius * Math.cos(mid));
var My = Cy + (radius * Math.sin(mid));
context.arc(Cx, Cy, radius, startA, endA, clockwise);
}
If you want the ellipse to fully fit inside a rectangle, it's really like this:
function ellipse(canvasContext, x, y, width, height){
var z = canvasContext, X = Math.round(x), Y = Math.round(y), wd = Math.round(width), ht = Math.round(height), h6 = Math.round(ht/6);
var y2 = Math.round(Y+ht/2), xw = X+wd, ym = Y-h6, yp = Y+ht+h6, cs = cards, c = this.card;
z.beginPath(); z.moveTo(X, y2); z.bezierCurveTo(X, ym, xw, ym, xw, y2); z.bezierCurveTo(xw, yp, X, yp, X, y2); z.fill(); z.stroke();
return z;
}
Make sure your canvasContext.fillStyle = 'rgba(0,0,0,0)'; for no fill with this design.