Getting the right width and height of a canvas element - html

I am having difficulties with setting the correct width and height of my canvas element.
I have a ball, that I'd like to bounce back whenever it hits a screen boundary by changing it's vertical velocity. It works, but instead of moving back as soon as it hits the edge of the screen, it goes on for a couple of seconds and THEN moves back. I have these variables to determine the viewport's size:
var left = 0,
right = canvas.width,
top = 0,
bottom = canvas.height;
If my ball's x or y positions are outside these boundaries, the velocity should be changed to a negative one. However, during my animation I console.log it's x position and by the time it reaches the right edge of the screen the value is around 600, which is really strange, since I'm on a 1366x768px monitor.
Also, it doesnt't fully reach the left screen edge, but bounces off like 50px from it.
Any ideas are really appreciated, because I've been stuck on this for quite some time.
You can see a working example here: http://codepen.io/gbnikolov/pen/puiwk

Update your draw to the following.
Ball.prototype.draw = function(ctx) {
ctx.save();
// you've translated to the x and y position of the ball.
ctx.translate(this.x, this.y);
ctx.rotate(this.rotation);
ctx.scale(this.scaleX, this.scaleY);
ctx.lineWidth = this.lineWidth;
ctx.fillStyle = this.color;
ctx.strokeStyle = this.strokeColor;
ctx.beginPath();
// Draw at 0,0 since we are already translated to the x and y.
ctx.arc(0, 0, this.radius, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.restore();
}
Live Demo
Your problem is in the draw method, you're translating the context and then making the arc at the x and y of the ball so if you translate to 20, 20 for example and then draw at 20,20 your ball is actually at 40,40.

Related

Why are artifacts visible in a scaled html5 canvas?

I've seen this and this discussion about removing antialiasing in canvases, but I don't think this is the same thing.
After scaling an html5 canvas by an arbitrary value (i.e., making it responsive), I've noticed that if I draw two rectangles of the same size and in the same location, the edges of the scaled side of the first rectangle remain visible.
I've included an example snippet where I draw a grey rectangle, then draw an red rectangle on top of it. There's a one-pixel red vertical line on the left and right edges of the grey rectangle. I know it may seem trivial, but it's very noticeable in my situation.
How do I fix this? Thanks!
var example = document.getElementById("example");
var ctx = example.getContext('2d');
ctx.scale(1.13,1);
ctx.fillStyle = "LightGrey";
ctx.fillRect(10,10,50,30);
ctx.fillStyle = "Black";
ctx.font = "20px Arial";
ctx.fillText("< Looks good.",70,30);
ctx.fillStyle = "Red";
ctx.fillRect(10,50,50,30);
// This light grey rectangle should completely cover the previous red one, but it doesn't!
ctx.fillStyle = "LightGrey";
ctx.fillRect(10,50,50,30);
ctx.fillStyle = "Black";
ctx.font = "20px Arial";
ctx.fillText("< Do you see red?",70,70);
<canvas id="example"></canvas>
You are scaling the transform matrix by a factor of 1.13 on the X axis.
So your coordinate 10, will actually end up on at coordinate 11.3 on the real pixels matrix.
You can't draw on fraction of pixels, so indeed antialiasing will kick in here.
So why does the first one looks better?
Because the mix between grey and white* is more neutral than the one between red grey and white. But even your first rect is antialiased.
Just zoom in your canvas and you'll see it, there is a one pixel band on both sides that is actually semi-transparent.
* "White" here is the one of the page's background
var example = document.createElement("canvas");
var ctx = example.getContext('2d');
ctx.scale(1.13,1);
ctx.fillStyle = "LightGrey";
ctx.fillRect(10,10,50,30);
ctx.fillStyle = "Red";
ctx.fillRect(10,50,50,30);
ctx.fillStyle = "LightGrey";
ctx.fillRect(10,50,50,30);
// draw bigger with no antialiasing
var z_ctx = zoomed.getContext('2d');
zoomed.width = example.width * 10;
zoomed.height = example.height * 10;
z_ctx.imageSmoothingEnabled = false;
z_ctx.drawImage(example, 0,0, zoomed.width, zoomed.height);
<canvas id="zoomed"></canvas>
So how to avoid this?
Well simply avoid filling at non integer pixel coordinates. This means you have to be constantly aware of your context transformation matrix too, not only of the values you pass to the drawing functions.
(Ps: also remember that stroke is an even eviler beast since it start drawing from the middle of the line, so in this case, you even have to take into considerations the lineWidth, see this Q/A on the matter).

How can I draw a line with lineTo in HTML5 that has angles to match the Unit Circle?

If I have this,
var canvas = document.getElementById("my-canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = '#f00';
ctx.beginPath();
ctx.moveTo(25, 25);
ctx.lineTo(150, 25);
ctx.rotate(Math.PI*7/4); //315 degrees
ctx.lineTo(150,90);
ctx.stroke();
It does not draw the line (the ctx.lineTo(150,90);) at the angle I thought it would which is from the end of the first lineTo at 25,25 to a 150,90 at a 45 degree angle. If I use -Math.PI*7/4 I get what looks like a 45 degree angle, but it points the wrong way. Math.PI*5/4 goes the wrong way or rotation.
My question asks about the Unit Circle. I don't really need them all at once, just the ability to know how to draw them if I need them.
The canvas is rotating this way:
Consider the following example, without the y offset:
Given by the code:
var canvas = document.getElementById("my-canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = '#f00';
ctx.beginPath();
ctx.moveTo(25, 0);
ctx.lineTo(250, 0);
ctx.rotate(45*Math.PI/180); //45 degrees
ctx.lineTo(150,0);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(0,0);
ctx.strokeStyle = '#ff0000';
ctx.lineTo(350,0);
ctx.font = "30px Arial";
ctx.fillText("New x axis",100,50);
ctx.stroke();
The red line is the new x axis, and the black line touches it exactly at a distance of 150 from the origin.
Now overlaying the same red line with your coordinates (and rotating by 45 degrees, so that it doesn't go off screen), we get
The black line ends at a point which is indeed (150,90), however at the new coordinate system. JSFiddle here
If you want the angle between the two line segments to be exactly what you pass in rotate(...), then keep drawing "horizontal" lines, but translate the origin to the end of each line segment, so you rotate about this point, not the top-left corner, using ctx.translate(<current point>). For example: https://jsfiddle.net/Douma37/65z1p38z/ (this goes off canvas, but has minimal interferance with your code).
Hope that helps!

Canvas inner stroke

I studied strokeStyle a bit but I cant find how to control the position of the stroke from inner/center/outer. It seems all stroke is outside the rectangle I draw. Is there anyway make the stroke be inner? (or even centered on the rectangle bounds)?
Thanks
Hope this helps!
Instead of doing:
ctx.fill();
ctx.stroke();
DO:
ctx.save();
ctx.clip();
ctx.lineWidth *= 2;
ctx.fill();
ctx.stroke();
ctx.restore();
Edit
For me I believe this works because the clip method removes any fill and stroke around the already present fill area, meaning the only place the stroke can go is on the inside because else it would be clipped off.
The default stroke do use centered stroke but there is unfortunately no parameter to control the alignment of the stroke so you would either have to calculate an offset value for the rectangle's position and size, or combine two rectangles and use for example the fill-rule evenodd:
var ctx = c.getContext("2d");
// default centered
ctx.lineWidth = 10;
ctx.strokeRect(10, 10, 100, 100);
ctx.lineWidth = 1;
ctx.strokeStyle = "red";
ctx.strokeRect(10, 10, 100, 100); // show main path
// inner
ctx.rect(150, 10, 100, 100);
ctx.rect(150+10, 10+10, 100-20, 100-20); // offset position and size
ctx.fill("evenodd"); // !important
ctx.strokeRect(150, 10, 100, 100);
<canvas id=c></canvas>
This answer "Draw outer and inner border around any canvas shape" shows how to use masking and compositing to precisely control the offset, both inwards and outwards of a stroke without the need to manipulate paths. It can be used for any canvas path no matter how complex.

Gradient stroke along canvas arc disappearing when context translates to center

I am very new to canvas drawings. I am trying to apply gradient along the arc of a circle. I can get it to appear fine when I draw the arc with center offset from the context coordinates. Lets say centerX and centerY denote the center of the canvas. I can get a gradient arc using context.arc(centerX, centerY, radius, ......).
Working example: http://jsfiddle.net/m5Pmb/
But when I try to draw the arc around the context coordinates, the gradient disappears. For example, I take the above working jsfiddle example, do context.translate(centerX, centerY), then do context.arc(0,0,radius,......), the resulting arc does not have any gradient on it.
Example here: http://jsfiddle.net/N6NMB/
In my case, I need to spin the resulting circle around its axis using context.rotate(), so I must translate to the center and draw circle around (0,0). But I cant understand why the gradient disappears when trying to draw arc around context's (0,0) point. Any insight would be really helpful.
Since you are translating the context centerX and centerY are not where you think anymore.
When you translate the context you are saying you want that x and y to be the new 0,0. So now your 0,0 is in the center of the canvas, so centerX and centerY are offset by themselves putting them further away from the center.
One method you can use is the following
var grad = context.createLinearGradient(
-radius,
radius / 2,
radius,
radius / 2
);
live Demo
The above works because its called after you translate the context, so centerX and centerY (like I said previously) are 0,0 meaning they don't need to be referenced in that function.
The gradients that you create will be painted with the actual transform in use.
So if you are not using any transform, no need to wonder anything : define your gradient where you're about to draw, and you'll be fine.
If you are using transform, you must think of the coordinates of the gradient as relative to the point/angle/scale when you'll use them.
To explain further, i modified your example and used a radial gradient.
I created a normalized gradient : it is defined in between 0.0 and 1.0 radius, meaning it will have its x and y in [-1; 1].
var eyeGrad = context.createRadialGradient(0, 0, 0, 0, 0, 1.0);
Then to use the gradient i must :
1) translate to be in the center of the figure i want to draw.
2) scale to have normalized coordinates.
function drawEye(x, y, r) {
context.save();
//translate context to center
context.translate(x, y);
// scale to radius
context.scale(r, r);
context.beginPath();
// draw an arc with radius of 1
context.arc(0, 0, 1, 0, 2 * Math.PI, false);
context.fillStyle = eyeGrad;
context.fill();
context.restore();
}
fiddle is here :
http://jsfiddle.net/gamealchemist/N6NMB/3/
Result for :
drawEye(100, 100, 40);
drawEye(250, 120, 20);

html5 canvas - emulate 3d rotation of image

I have an image which has square shape. I want to rotate and squeeze it to get 3d effect like on the pictures below:
Source image:
Rotate to 0 degrees and squeeze:
Rotate to 45 degrees and squeeze:
Something like this.
I have played around Math and tried to change Width and Height of the image by multiplying to Sin and Cos of angle.
var w = image.width*Math.cos(angle* TO_RADIANS);
var h = image.height*Math.sin(angle* TO_RADIANS);
h=h*2/3; //squeezing the height
ctx.drawImage(image, 0, 0, w, h);
But I am not good at mathematics, so I hope somebody may help me to solve this issue.
I've resolved my problem. I squeezed my image in photoshop. So, the image became 300x150 size and looked like the second picture above. Then I applied a function below anytime, when I needed to redraw the image according to the angle:
var TO_RADIANS = Math.PI/180;
ctx.save();
ctx.translate(x, y);
ctx.rotate(angle * TO_RADIANS);
var w = image.width-Math.abs((image.width/2)*Math.sin(angle* TO_RADIANS));
var h = image.height+Math.abs((image.height)*Math.sin(angle * TO_RADIANS));
ctx.translate(-w/2, -h/2);
ctx.drawImage(image, 0, 0, w, h);
ctx.restore();
Now it works pretty well.
You should look into a transform matrix.
Something like this:
ctx.transform(1, 0.6, -.8, .5, 20, 0);
http://jsfiddle.net/ericjbasti/nNZLC/
some links for you :
http://www.w3schools.com/tags/canvas_transform.asp
https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/HTML-canvas-guide/MatrixTransforms/MatrixTransforms.html