Bouncing Ball On JavaScript with background and a Gradient - javascript

Hello I'm trying to create a ball on JavaScript that possess a background with a Gradient as the ball passes by, by far my code for the ball bouncing seems to work, when I try to fill the background with:
context.fillStyle = "rgba(0,0,0,0.10)"; //this is what i am trying to do as the gradient
context.fillRect(0,0, canvas.width, canvas.height);
is when I mess everything up I'm not sure what am i doing wrong any help is kindly apprecciated, the one below is the approach I have taken for the bouncing ball :
<script>
var context;
var posX=100;
var posY=200;
var dx=5;
var dy=5;
function bouncyBall()
{
var canvas = document.getElementById("circleCanvas");
context= canvas.getContext('2d');
setInterval(draw,10);
}
function draw()
{
context.clearRect(0,0, 800,600);
context.beginPath();
context.fillStyle="orange";
//to draw the circle
context.arc(posX,posY,20,0,Math.PI*2,true);
context.closePath();
context.fill();
// this will do the boundares
if( posX<0 || posX>800) dx=-dx;
if( posY<0 || posY>600) dy=-dy;
posX = posX+dx;
posY = posY+dy;
}
</script>
<body onload= "bouncyBall();" >
<h1>A Ball Bouncing!</h1>
<canvas id = "circleCanvas" width="800" height="600">
</canvas>
<ul>
</ul>
</body>
</html>

Here's how you create a linear gradient for use on your ball-canvas:
// think of createLinearGradient as a line
// the gradient will follow that line
var orangeGradient = context.createLinearGradient(
canvas.width/2, 0, canvas.width/2, canvas.height);
// then define where each color will be along the line
// (0.00==start of line,1.00==end of line)
orangeGradient.addColorStop(0, '#ffdd00');
orangeGradient.addColorStop(1, '#cc6600');
// and finally set the fillStyle to your new gradient
context.fillStyle = orangeGradient;
context.fill();

Related

How to get true 1-pixel width black color line in p5.js [duplicate]

When i try to draw single pixel black line with the following code:
context.strokeStyle = '#000';
context.beginPath();
context.moveTo(x1, y1);
context.lineTo(x2, y2);
context.lineWidth = 1;
context.stroke();
context.closePath();
I have more then one pixel line with gray border. How to fix it?
Here is an example http://jsfiddle.net/z4VJq/
Call your function with these coordinates instead: drawLine(30,30.5,300,30.5);. Try it in jsFiddle.
The problem is that your color will be at an edge, so the color will be halfway in the pixel above the edge and halfway below the edge. If you set the position of the line in the middle of an integer, it will be drawn within a pixel line.
This picture (from the linked article below) illustrates it:
You can read more about this on Canvas tutorial: A lineWidth example.
You have to use context.translate(.5,.5); to offset everything by half a pixel. Its easy way for fix your problem
var canvas = document.getElementById("canvas1");
var context1 = canvas.getContext('2d');
context1.strokeStyle = '#000';
context1.beginPath();
context1.moveTo(10, 5);
context1.lineTo(300, 5);
context1.stroke();
var canvas2 = document.getElementById("canvas2");
var context2 = canvas2.getContext('2d');
context2.translate(.5,.5);
context2.strokeStyle = '#000';
context2.beginPath();
context2.moveTo(10, 5);
context2.lineTo(300, 5);
context2.stroke();
<div><canvas height='10' width='300' id='canvas1'>Обновите браузер</canvas></div>
<div><canvas height='10' width='300' id='canvas2'>Обновите браузер</canvas></div>

Draw fixed boxes on HTML canvas image [duplicate]

I'm tyring to rotate a diagram in canvas around its center while keeping the letters upright. I'm trying to use ctx.rotate(#) but it's rotating the entire diagram using what appears to be the left side of the canvas as the center.
The following link offers a visual: I want it to look like the green, not the red, as it currently does with my code. Visual Explanation
The following is the JSFiddle: http://jsfiddle.net/ddxarcag/143/
And my code is below:
<script>
$(document).ready(function () {
init();
function init() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
draw(ctx);
}
function draw(ctx) {
// layer1/Line
ctx.rotate(00);
ctx.beginPath();
ctx.moveTo(75.1, 7.7);
ctx.lineTo(162.9, 7.7);
ctx.stroke();
function WordSelector1() {
var word = ['A', 'B', 'C'];
var random = word[Math.floor(Math.random() * word.length)];
return random;
}
var x = WordSelector1();
// layer1/P
ctx.font = "12.0px 'Myriad Pro'";
ctx.rotate(0);
ctx.fillText(x, 60.0, 10.0);
}
});
</script>
Any help would be much appreciated. Thanks!
Drawing rotated graphs in canvas is somewhat easy once you know how to move the origin (0,0) to another point and then rotating the axes around it.
I added some comments in the code as not to repeat code and explanations.
I also moved the functions out of the $(document).ready and changed some numbers for more rounded values.
$(document).ready(function () {
init();
});
function init() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
draw(ctx);
}
function draw(ctx) {
ctx.font = "12.0px 'Myriad Pro'";
var angle = Math.random()*150; //Run more times to see other angles
//This translates the 0,0 to the center of the horizontal line
ctx.translate(100, 100);
//This draws the original straight line
ctx.beginPath();
ctx.moveTo(-50, 0); //The coordinates are relative to the new origin
ctx.lineTo(50, 0);
ctx.stroke();
//Draw the first letter
var x = WordSelector1();
ctx.fillText(x, -60, 0);
//This section draws the rotated line with the text straight
//Rotate the canvas axes by "angle"
ctx.rotate(angle * Math.PI/180);
ctx.beginPath();
ctx.moveTo(-50, 0); //The relative coordinates DO NOT change
ctx.lineTo(50, 0); //This shows that the axes rotate, not the drawing
ctx.stroke();
var x = WordSelector1();
ctx.translate(-60,0); //The origin must now move where the letter is to be placed
ctx.rotate(-angle * Math.PI/180); //Counter-rotate by "-angle"
ctx.fillText(x, 0, 0); //Draw the letter
}
function WordSelector1() {
var word = ['A', 'B', 'C'];
var random = word[Math.floor(Math.random() * word.length)];
return random;
}
canvas{
border: 1px solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width="200" height="200"></canvas>
One warning: after everything is drawn the axes end parallel to the canvas borders because it was rotated by -angle, but the origin is where the last letter was placed. You may want to use ctx.save() and ctx.restore() to avoid having to revert translations and rotations.

Clean text from canvas shapes

How I clean text from canvas shape ?
this my code:
<div id="ways" style="width:1000px;margin:0 auto;height:100%;">
<canvas id="canvas" width="1000" height="1000"></canvas>
and fiddle
Just refactor the code a bit -
Extract the lines which draws the circle into a single function which takes one of those circle objects as an argument:
function drawCircle(circle) {
context.beginPath();
context.arc(circle.x, circle.y, circle.radius, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill();
context.lineWidth = lineWidth;
context.strokeStyle = '#003300';
context.stroke();
}
Then replace those lines which they came from originally, in the loop with this line (after the circle object has been pushed):
drawCircle(circles[circles.length-1]); // draw last added circle
Now you can use this function in your click events by modifying the code (here, it toggles text on and off):
if (context.isPointInPath(x, y)) {
if (circle.clicked) {
drawCircle(circle); // now we can reuse this function to clear the text
circle.clicked = false;
}
else {
circle.clicked = true;
context.fillStyle = "blue";
context.font = "bold 34px Arial";
context.textAlign="center";
context.fillText("Yeah", circle.x, circle.y);
}
break;
}
Modified fiddle
Just a note with this approach: this will redraw the circles on top of each other. Over time the lines will start to look jaggy due to the added anti-aliasing on the edges. For this reason a full clear of the canvas is better, and then redraw them all. But I'll leave that as an exercise for you.. :-)

html5 javascript fillstyle doesnt work

I'm dabbling with html5 and javascript (I know nothing of both). I found an example of some html5, copied it, and started experimenting. Heres some code. The idea is that when any key is pressed, two squares start moving left (doesn't clean up behind it yet). What I don't understand is why I cant change colour (Ive indicated below). Any ideas? Im obviously doing something very wrong.
<!doctype html>
<!-- this source copied from http://www.xanthir.com/blog/b48B0 -->
<canvas width=800 height=800>
</canvas>
<script>
var canvas = document.getElementsByTagName("canvas")[0];
var context = canvas.getContext('2d');
var x = 230;
var y = 380;
// First, we'll paint the whole canvas black.
context.fillStyle = "black";
context.fillRect(0,0,800,800);
context.fillStyle = "red";
context.fillRect(0,0,30,30);
context.fillRect(0,100,30,30);
context.fillStyle = "green";
context.fillRect(0,200,30,30);
// Now we'll draw some shapes
// circle
context.fillStyle = "#06c";
context.strokeStyle = "white";
// These can be any CSS color.
context.lineWidth = 3;
context.beginPath();
context.moveTo(450,250);
context.arc(375,250,75,0,2*Math.PI,false)
context.closePath();
context.fill();
context.stroke();
// A triangle! And a rainbow!
context.beginPath();
context.moveTo(150,50);
context.lineTo(90,150);
context.lineTo(210,150);
context.lineTo(150,50);
context.closePath();
var rainbow = context.createLinearGradient(150,50,150,150);
rainbow.addColorStop(.1,"red");
rainbow.addColorStop(.3,"orange");
rainbow.addColorStop(.5,"yellow");
rainbow.addColorStop(.7,"lime");
rainbow.addColorStop(.9,"blue");
context.fillStyle = rainbow;
context.fill();
// Some text! And a shadow!
context.shadowOffsetX = -2;
context.shadowOffsetY = 2;
context.shadowColor = "#f88";
context.shadowBlur = .01;
context.fillStyle = "red";
context.font = "bold 72px monospace";
context.fillText("Foo Bar",30,400);
context.fillStyle = "blue";
context.fillRect(0,300,30,30);
// ???????????? end of main. The current context now seems to remain (blue fillstyle with some shadow )
// routine here : press any key to animate two new blocks over writing ----------------
document.onkeydown = function(e) {
context.fillstyle = "red"; // <-- ???????? this doesnt work (remains same colour as last one in main )
context.fillRect(x,y,50,50); // <-- ???????? draws a square in blue, not red
x = x - 5;
context.fillstyle = "white"; // <-- ???????? this doesnt work (remains same colour as last one in main )
context.fillRect(x -100,y ,50,50); // <-- ???????? draws a square in blue, not white
}
Because you wrote fillstyle and not fillStyle. You need to capitalize the S.
It is valid in Javascript because you are just attaching a new fillstyle field (which does not exist and is meaningless) to that context.
So you gotta be careful. Typos can cause lots of trouble, because the resulting code isn't technically an error, but its certainly not what you want!

Rotate 'note' on the canvas to always touch the upper left corner

The final code that worked for me was:
<canvas id="bg-admin-canvas" width="500" height="500" style="margin:15px; background:#09F;"></canvas>
<script>
var postit = function(width,height,angle){
var canvas = document.getElementById("bg-admin-canvas");
var ctx = canvas.getContext("2d");
var radians = angle * Math.PI / 180;
var move = width*Math.sin(radians);
if(angle < 0 ){ ctx.translate(0,-move); }else{ ctx.translate(move,0); }
ctx.rotate(radians);
var gradient = ctx.createLinearGradient(0,height,width/2,height/2);
gradient.addColorStop(0.05,"rgba(0,0,0,0)");
gradient.addColorStop(0.5,"rgba(0,0,0,0.3)");
ctx.fillStyle = gradient;
ctx.fillRect(0,0,width,height);
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(width, 0);
ctx.lineTo(width,height);
ctx.lineTo(width-width*.8,height-height*.02);
ctx.quadraticCurveTo(0+width*.02,height-height*.02,0+width*.02,(height - height*.2));
ctx.closePath();
var gradient = ctx.createLinearGradient(0,height,width/2,height/2);
gradient.addColorStop(0,'#f7f8b9');
gradient.addColorStop(1,'#feffcf');
ctx.fillStyle = gradient;
ctx.fill();
ctx.beginPath();
ctx.moveTo(width-width*.8,height-height*.02);
ctx.quadraticCurveTo(0+width*.02,height-height*.02,0+width*.02,(height - height*.2));
ctx.quadraticCurveTo(width*.05,height-height*.05,width*.1,height-height*.1);
ctx.quadraticCurveTo(width*.1,height-height*.07,width-width*.8,height-height*.02);
ctx.closePath();
ctx.fillStyle = '#ffffff';
ctx.fill();
var gradient = ctx.createLinearGradient(0,height,width*.1,height-height*.1);
gradient.addColorStop(0,"rgba(222,222,163,0.8)");
gradient.addColorStop(1,'#feffcf');
ctx.fillStyle = gradient;
ctx.fill();
}
postit(300, 300, 10);
</script>
Hi,
I made a quick and dirty "post-it" note with html5's canvas and some js.
I want to be able to rotate them anyway I want so I tried to use the translate. The example below I have a translate of 0,250 just so you could see the whole thing.
Ideally, I know if my canvas was 300,300 then I would
ctx.translate(150,150);
ctx.rotate(-30);
ctx.translate(-150,-150);
Of course since I'm rotating a square it gets cut off.
How would I rotate the square and move it on the canvas so the whole thing is showing but at the very top left edge of the canvas?
I added an image with my thinking of just getting the height of a triangle and moving it that much, but when translated, it doesn't seem to work just right.
I'll paste my whole function so you can look at it, but if you have any ideas, I would appreciate it. This isn't important, just messing around today.
var postit = function(width,height,angle){
var canvas = jQuery("#bg-admin-canvas").get(0);
var ctx = canvas.getContext("2d");
/*var area = (width*width*Math.sin(angle))/2;
var h = (area*2) / width + 30;
ctx.translate(0,h);
*/
//ctx.translate(150,150);
ctx.translate(0,250);
ctx.rotate(angle*Math.PI / 180);
//ctx.translate(-150,-150);
var gradient = ctx.createLinearGradient(0,height,width/2,height/2);
gradient.addColorStop(0.05,"rgba(0,0,0,0)");
gradient.addColorStop(0.5,"rgba(0,0,0,0.3)");
ctx.fillStyle = gradient;
ctx.fillRect(0,0,width,height);
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(width, 0);
ctx.lineTo(width,height);
ctx.lineTo(width-width*.8,height-height*.02);
ctx.quadraticCurveTo(0+width*.02,height-height*.02,0+width*.02,(height - height*.2));
ctx.closePath();
var gradient = ctx.createLinearGradient(0,height,width/2,height/2);
gradient.addColorStop(0,'#f7f8b9');
gradient.addColorStop(1,'#feffcf');
ctx.fillStyle = gradient;
ctx.fill();
ctx.beginPath();
ctx.moveTo(width-width*.8,height-height*.02);
ctx.quadraticCurveTo(0+width*.02,height-height*.02,0+width*.02,(height - height*.2));
ctx.quadraticCurveTo(width*.05,height-height*.05,width*.1,height-height*.1);
ctx.quadraticCurveTo(width*.1,height-height*.07,width-width*.8,height-height*.02);
ctx.closePath();
ctx.fillStyle = '#ffffff';
ctx.fill();
var gradient = ctx.createLinearGradient(0,height,width*.1,height-height*.1);
gradient.addColorStop(0,"rgba(222,222,163,0.8)");
gradient.addColorStop(1,'#feffcf');
ctx.fillStyle = gradient;
ctx.fill();
}
postit(300, 300, -35);
MORE INFO
Phrog, I think you know what I'm trying to do. This image shows what I want to do:
Now, the only thing is, I want to be able to pass in any width and height and angle and make the adjustment on the fly.
As an example with the following code:
var canvas = document.getElementById("bg-admin-canvas");
var ctx = canvas.getContext("2d");
ctx.arc(0,0,3,0,360,true); ctx.fill();
ctx.translate(50, 50);
ctx.arc(0,0,3,0,360,true); ctx.fill();
ctx.translate(-25, -25);
ctx.arc(0,0,3,0,360,true); ctx.fill();
I get the following image:
Now, if I add a rotate in there like this:
var canvas = document.getElementById("bg-admin-canvas");
var ctx = canvas.getContext("2d");
ctx.arc(0,0,3,0,360,true); ctx.fill();
ctx.translate(50, 50);
ctx.arc(0,0,3,0,360,true); ctx.fill();
ctx.rotate(30*Math.PI/180);
ctx.translate(-25, -25);
ctx.arc(0,0,3,0,360,true); ctx.fill();
I now have a sloped coordinates as the result is:
As I found, this is because the coordinates are no longer horizontal and vertical.
So, with this rotated coordinate structure, I can't figure out how to move my square (which could be any size and rotated at any angle) back to the left and top (so it fits in as little space as possible)
Does that make sense?
In short:
Translate the context in the Y direction only to put the corner where it should be.
Rotate the context around this offset point.
Draw your object at 0,0.
Here is an interactive, working example, which you can see online here:
http://phrogz.net/tmp/canvas_rotate_square_in_corner.html
<!DOCTYPE HTML>
<html lang="en"><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>HTML5 Canvas Rotate Square in Corner</title>
<style type="text/css" media="screen">
body { background:#eee; margin:2em; text-align:center }
canvas { display:block; margin:auto; background:#fff; border:1px solid #ccc }
</style>
</head><body>
<canvas width="250" height="200"></canvas>
<script type="text/javascript" charset="utf-8">
var can = document.getElementsByTagName('canvas')[0];
var ctx = can.getContext('2d');
ctx.strokeStyle = '#600'; ctx.lineWidth = 2; ctx.lineJoin = 'round';
ctx.fillStyle = '#ff0'
document.body.onmousemove = function(evt){
var w=140, h=120;
var angle = evt ? (evt.pageX - can.offsetLeft)/100 : 0;
angle = Math.max(Math.min(Math.PI/2,angle),0);
ctx.clearRect(0,0,can.width,can.height); ctx.beginPath();
ctx.save();
ctx.translate(1,w*Math.sin(angle)+1);
ctx.rotate(-angle);
ctx.fillRect(0,0,w,h);
ctx.strokeRect(0,0,w,h);
ctx.restore();
};
document.body.onmousemove();
</script>
</body></html>
Analysis
In the above diagram, point A is the upper-left corner of our post-it note and point B is the upper-right corner. We have rotated the post-it note -a radians from the normal angle (clockwise rotations are positive, counter-clockwise are negative).
We can see that the point A stays on the y axis as the post-it rotates, so we only need to calculate how far down the y axis to move it. This distance is expressed in the diagram as BD. From trigonometry we know that
sin(a) = BD / AB
Rearranging this formula gives us
BD = AB * sin(a)
We know that AB is the width of our post-it note. A few details:
Because our angle will be expressed as a negative number, and the sin of a negative number yields a negative result, but because we want a positive result, we must either negate the result
BD = -AB * sin(-a)
or just 'cheat' and use a positive angle:
BD = AB * sin(a)
We need to remember to translate our context before we rotate it, so that we first move directly down the axis to establish our origin at the right spot.
Remember that rotations in HTML5 Canvas use radians (not degrees). If you want to rotate by 20 degrees, you need to convert that to radians by multiplying by Math.PI/180:
ctx.rotate( 20*Math.PI/180 );
This also applies to the arc command; you should be doing ctx.arc(x,y,r,0,Math.PI*2,false); for a full circle.
You should create you canvas element and then rotate it using CSS. It would keep your canvas intact and only rotate the element itself.
Here is some example css rules:
-webkit-transform: rotate(-30deg);
-moz-transform: rotate(-30deg);
Refer to http://snook.ca/archives/html_and_css/css-text-rotation

Categories

Resources