I don't know what I did wrong about this code.
I've tried redoing the entire script many times, and even renamed it to see if it would change anything but it didn't.
<!DOCTYPE html>
<html>
<head>
<title>Purely's Tower Defense</title>
<style>
* { padding: 0; margin: 0; }
canvas {background: #eee; display: block; margin: 0 auto}
</style>
</head>
<body>
<canvas id="myCanvas" width='800' height='500'></canvas>
<script type="text/javascript">
var canvas = document.getElementById('myCanvas');
var ctx = myCanvas.getContext('2d');
var playerX = (canvas.width - playerWidth)/2;
var playerY = canvas.height - playerHeight;
var playerWidth = 30;
var playerHeight = 30;
function drawPlayer()
{
ctx.beginPath();
ctx.fillStyle = "#000000";
ctx.fillRect(playerX, playerY, playerWidth, paddleHeight);
ctx.closePath()
}
function draw()
{
ctx.clearRect(0,0,canvas.width,canvas.height);
drawPlayer();
}
draw();
</script>
</body>
</html>
I expected to just have the crystal & the player to spawn.
You have two separate issues in your code:
You are defining playerX and playerY based on the playerWidth and playerHeight before they are defined
You are using paddleHeight instead of playerHeight in your drawPlayer function.
To fix this, you need to change your variable declaration order to have playerWidth and playerHeight before X and Y:
var canvas = document.getElementById('myCanvas');
var ctx = myCanvas.getContext('2d');
var playerWidth = 30;
var playerHeight = 30;
var playerX = (canvas.width - playerWidth)/2;
var playerY = canvas.height - playerHeight;
And change your drawPlayer function to use playerHeight
function drawPlayer()
{
ctx.beginPath();
ctx.fillStyle = "#000000";
ctx.fillRect(playerX, playerY, playerWidth, playerHeight);
ctx.closePath();
}
Related
I'm trying to make a ball jump even in midair, but my code always just teleports to the same spot and then jumps, can anydody tell me how to fix this problem of mine? It needs to be able to jump wherever it is at that exact moment, and i've already tried something with set interval.
I'm trying to make a ball jump even in midair, but my code always just teleports to the same spot and then jumps, can anydody tell me how to fix this problem of mine? It needs to be able to jump wherever it is at that exact moment, and i've already tried something with set interval.
I'm trying to make a ball jump even in midair, but my code always just teleports to the same spot and then jumps, can anydody tell me how to fix this problem of mine? It needs to be able to jump wherever it is at that exact moment, and i've already tried something with set interval.
var canvas, ctx, container;
canvas = document.createElement('canvas');
ctx = canvas.getContext("2d");
var ball;
var touchGround = false;
var pull= 0.43;
var vy;
var gravity = pull;
var i = Math.floor(Math.random()*11)
color = ["red", "blue","green","yellow","purple","white","pink","silver","teal","turqu oise","magenta","cyan"];
console.log(color[i])
function ballMovement() {
vy += gravity;
ball.y += vy;
if (ball.y + ball.radius > canvas.height) {
ball.y = canvas.height - ball.radius;
vy = 0;
var img = document.getElementById('gameOver');
ctx.drawImage(gameOver, canvas.width/2-436, 100)
ball.radius = 0;
}
}
function init() {
setupCanvas();
var img = document.getElementById('gameOver');
img.style.visibility = 'hidden';
//how high the ball goes
vy = -19;
var y1 = 450
ball = {
x: canvas.width/2,
//where the ball starts moving upwards
y: 480, //here1
radius: 20,
status: 0,
color: color[i]};
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2, false);
ctx.fillStyle = ball.color;
ctx.fill();
ctx.closePath()
//draw a moving ball
ballMovement();
}
setInterval(draw, 1000 / 35);
function setupCanvas() {
container = document.createElement('div');
container.className = "container";
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(container);
container.appendChild(canvas);
ctx.strokeStyle = "#ffffff";
ctx.lineWidth = 2;
}
window.onclick = function(jump){
pull + 0.1;
touchGround = false;
init()
draw()
ballMovement()
setupCanvas()
vy+((canvas.height-canvas.height)-ball.y);
}
//GOAL
//Ball jumps at somewhere in screen, let it jump wherever it is.
If I got you correctly you want your ball to go higher and higher. But problem is that you got fixed position where it's starts so where's what you need to change:
var canvas, ctx, container;
canvas = document.createElement('canvas');
canvas.width = 800;
canvas.height = 800;
ctx = canvas.getContext("2d");
var ball = {
y: 480
};
var touchGround = false;
var pull= 0.43;
var vy;
var gravity = pull;
//Creating a variable to know whether our game is running
var gameRunning = 0;
var i = Math.floor(Math.random()*11);
//Adding variable for interval so we can start it with init function
var timer;
color = ["red", "blue","green","yellow","purple","pink","silver","teal","turquoise","magenta","cyan", "black"];
function ballMovement() {
vy += gravity;
ball.y += vy;
if (ball.y + ball.radius > canvas.height) {
ball.y = canvas.height - ball.radius;
vy = 0;
var img = document.getElementById('gameOver');
ctx.drawImage(gameOver, canvas.width/2-436, 100)
ball.radius = 0;
//Stoping the draw function
clearInterval(timer);
//Saying the game isn't running
gameRunning = 0;
}
}
function init() {
//Check if canvas already created
if(!document.querySelector('.container')){
setupCanvas()
}
vy = -19;
var y1 = 450
ball = {
x: canvas.width/2,
y: ball.y,
radius: 20,
status: 0,
color: color[i]
};
//Clearing previous interval if it were any and creating a new one
clearInterval(timer);
timer = setInterval(draw, 1000 / 60);
//Saying the game is running
gameRunning = 1;
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2, false);
ctx.fillStyle = ball.color;
ctx.fill();
ctx.closePath()
ballMovement();
}
function setupCanvas() {
container = document.createElement('div');
container.className = "container";
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(container);
container.appendChild(canvas);
ctx.strokeStyle = "#ffffff";
ctx.lineWidth = 2;
}
window.onclick = function(){
pull + 0.1;
touchGround = false;
//Check if the game is running or not
//If it's not running - call init
if(!gameRunning){
init();
}
else{
//If game is already running - change speed
vy = -19;
}
//I've also removed some function that were starting with init itself
vy+((canvas.height-canvas.height)-ball.y);
}
I am trying to calculate and display the circumference by retrieving the already defined radius from the given code of a drawn circle. Is it the way I typed out the formula wrong or does it need to be in the same script section?
function draw() {
var canvas = document.getElementById('circle');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
var X = canvas.width / 2;
var Y = canvas.height / 2;
var R = 45;
ctx.beginPath();
ctx.arc(X, Y, R, 0, 2 * Math.PI, false);
ctx.lineWidth = 3;
ctx.strokeStyle = '#FF0000';
ctx.stroke();
}
}
function calculatecircumference() {
var circumference = ((2) * (Math.Pi) * (R));
}
document.getElementById("Circumference").innerHTML = circumference;
<!Doctype>
<html>
<body onload="draw();">
<canvas id="circle" width="150" height="150"></canvas>
</body>
<p>Circumference: <span id="Circumference"></span></p>
</html>
Actually the math PI is wrong....you have written Math.Pi
var circumference = ((2) * (Math.Pi) * (R));
but in actual it is Math.PI
var circumference = ((2) * (Math.PI) * (R));
Hence it Returns a NaN for a radius of 45 ..
Check the working below code.... also you need to call the calculatecircumference function..and pass the Radius as param
function draw() {
var canvas = document.getElementById('circle');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
var X = canvas.width / 2;
var Y = canvas.height / 2;
var R = 45;
ctx.beginPath();
ctx.arc(X, Y, R, 0, 2 * Math.PI, false);
ctx.lineWidth = 3;
ctx.strokeStyle = '#FF0000';
ctx.stroke();
calculatecircumference(R);
}
}
function calculatecircumference(R) {
var circumference = ((2) * (Math.PI) * (R));
document.getElementById("Circumference").innerHTML = circumference;
}
<body onload="draw();">
<canvas id="circle" width="150" height="150"></canvas>
</body>
<p>Circumference: <span id="Circumference"></span></p>
You have three problems:
First, you need to give calculatecircumference() scope to access R. This can be done by calling calculatecircumference() from within draw() and passing it through as a function parameter. You'll also need to tell calculatecircumference() that its function parameter should be assigned to the local variable R, by writing it as calculatecircumference(R).
Second, document.getElementById("Circumference").innerHTML does not have access to the scope of circumference. Simply run the line document.getElementById("Circumference").innerHTML = circumference line inside caluclatecircumference().
Finally, you called Math.Pi instead of Math.PI in calculatecircumference(). The PI must be uppercase.
Correcting these three issues fixes the problem, as can be seen below:
function draw() {
var canvas = document.getElementById('circle');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
var X = canvas.width / 2;
var Y = canvas.height / 2;
var R = 45;
ctx.beginPath();
ctx.arc(X, Y, R, 0, 2 * Math.PI, false);
ctx.lineWidth = 3;
ctx.strokeStyle = '#FF0000';
ctx.stroke();
calculatecircumference(R);
}
}
function calculatecircumference(R) {
var circumference = ((2) * (Math.PI) * (R));
document.getElementById("Circumference").innerHTML = circumference;
}
<!Doctype>
<html>
<body onload="draw();">
<canvas id="circle" width="150" height="150"></canvas>
</body>
<p>Circumference: <span id="Circumference"></span></p>
</html>
Hope this helps! :)
I've been working on a chunk of code for a would-be Sierpinski fractal animation, but for some reason, the animation part just doesn't seem to work. I also tried using setInterval(), with the same results, namely a blank canvas. The idea is to draw an equilateral triangle with vertex coordinates as parameters step by step, as though somebody was drawing it on a piece of paper. Could you have a look to see what's wrong with it?
On a side note, I've copied a few examples of canvas animation off a few web tutorials, and none of them appear to be working in my files either. I use Firefox and Chrome, both up to date, so I guess it's not a technical issue.
<!DOCTYPE html>
<style>
canvas {
width: 600px;
height: 600px;
text-align: center;
background-color: white;
background-position: center;
position: relative;
top: 0px;
left: 0px;
border:1px solid #d3d3d3;
}
<body>
<canvas id="sCanvas"></canvas>
<script>
This is where the animation is supposed to take place; draws a line from (Ax,Ay) to (Bx,By).
function lineAnimation(x1,y1,x2,y2,ctx) {
var deltaX = (x2 - x1) / 100;
var deltaY = (y2 - y1) / 100;
var x = x1;
var y = y1;
var timer = setInterval(function () {
ctx.moveTo(x,y);
ctx.lineTo(x+deltaX,y+deltaY);
ctx.stroke();
x += deltaX;
y += deltaY;
}, 100);
if ((x===x2) && (y===y2)) clearTimeout(timer);
}
function drawTriangle(Ax,Ay,Bx,By,Cx,Cy,ctx) {
lineAnimation(Ax,Ay,Bx,By,ctx);
lineAnimation(Bx,By,Cx,Cy,ctx);
lineAnimation(Cx,Cy,Ax,Ay,ctx);
}
function init() {
var canvas=document.getElementById("sCanvas");
var ctx = canvas.getContext("2d");
ctx.save();
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.strokeStyle = 'black';
ctx.lineWidth = 2;
drawTriangle(10,10,30,50,50,10);
}
init();
</script>
Your functions are requiring the parameter ctx which you didn't include, as such they don't know what ctx is. All you need to do is include it in drawTriangle():
drawTriangle(10,10,30,50,50,10,ctx);
And then everything works.
Try This
function lineAnimation(x1,y1,x2,y2,ctx) {
var deltaX = (x2 - x1) / 100;
var deltaY = (y2 - y1) / 100;
var x = x1;
var y = y1;
var timer = setInterval(function () {
var canvas=document.getElementById("sCanvas"); //Added Change
var ctx = canvas.getContext("2d"); //Added Change
ctx.moveTo(x,y);
ctx.lineTo(x+deltaX,y+deltaY);
ctx.stroke();
x += deltaX;
y += deltaY;
}, 100);
if ((x===x2) && (y===y2)) clearTimeout(timer);
}
function drawTriangle(Ax,Ay,Bx,By,Cx,Cy,ctx) {
lineAnimation(Ax,Ay,Bx,By,ctx);
lineAnimation(Bx,By,Cx,Cy,ctx);
lineAnimation(Cx,Cy,Ax,Ay,ctx);
}
function init() {
var canvas=document.getElementById("sCanvas");
var ctx = canvas.getContext("2d");
ctx.save();
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.strokeStyle = 'black';
ctx.lineWidth = 2;
drawTriangle(10,10,30,50,50,10);
}
init();
It is giving you an error over ctx.moveTo(x,y); and ctx.lineTo(x+deltaX,y+deltaY); because thet are not able to use you ctx which is basically an object of your canvas. so just try to add them in code and things will work fine
DEMO
I'm trying to animate a sine wave in JS but it's not acting as expected. I'm using a <canvas> element along with window.requestAnimationFrame() method but it's a CPU hog and as i change frequency with the slider it just break and show random waveforms. I also don't know if drawing adjacent lines is the best way to represent a sine wave. Please note that i'll use vanilla JS and that the sine's frequency and amplitude are variables set by sliders. Thanks in advance.
This is what i got so far: http://cssdeck.com/labs/8cq5vclp
UPDATE: i worked on it and this is the new version: http://cssdeck.com/labs/sbfynjkr
var canvas = document.querySelector("canvas"),
ctx = canvas.getContext("2d"),
cHeight = canvas.height,
cWidth = canvas.width,
frequency = document.querySelector("#f").value,
amplitude = 80,
x = 0,
y = cHeight / 2,
point_y = 0;
window.onload = init;
function init() {
document.querySelector("#f").addEventListener("input", function() {
frequency = this.value;
document.querySelector("#output_f").value = frequency;
}, false);
drawSine();
}
function drawSine() {
ctx.clearRect(0, 0, cWidth, cHeight);
ctx.beginPath();
ctx.moveTo(0, y);
ctx.strokeStyle = "red";
ctx.lineTo(cWidth, y);
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.strokeStyle = "black";
for (x = 0; x < 600; x++) {
point_y = amplitude * -Math.sin((frequency / 95.33) * x) + y;
ctx.lineTo(x, point_y);
}
ctx.stroke();
ctx.closePath();
requestAnimationFrame(drawSine);
}
canvas {
border: 1px solid red;
margin: 10px;
}
<input id="f" type="range" min="0" max="20000" value="20" step="1">
<output for="f" id="output_f">20</output>
<canvas width="600px" height="200px"></canvas>
I've messed around with sine waves quite a bit, because I'm working on a little project that involves animated sine waves. I've got some code you might be interested in taking a look at. Like mentioned earlier, you need to make sure you are using the right increment in your loop so the lines do not look jagged.
https://jsfiddle.net/uawLvymc/
window.requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(f) {
return setTimeout(f, 1000 / 60)
};
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var startTime = new Date().getTime();
function getPath(height) {
var width = canvas.width;
var spacing = 0.08;
var loopNum = 0;
var pointList = [];
var i = 0;
for (i = 0; i < width / 2; i++) {
pointList[loopNum] = [loopNum, Math.sin(loopNum * spacing) * (i * height) + 100];
loopNum++;
}
for (i = width / 2; i > 0; i--) {
pointList[loopNum] = [loopNum, Math.sin(loopNum * spacing) * (i * height) + 100];
loopNum++;
}
return pointList;
}
function draw() {
var currentTime = new Date().getTime();
var runTime = currentTime - startTime;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.lineWidth = 2;
ctx.strokeStyle = "rgb(80, 100, 230)";
var height = Math.sin(runTime * 0.008) * 0.2;
var pointList = getPath(height);
for (var i = 0; i < 500; i++) {
if (i === 0) {
ctx.moveTo(pointList[0][0], pointList[0][1]);
} else {
ctx.lineTo(pointList[i][0], pointList[i][1]);
}
}
ctx.stroke();
window.requestAnimationFrame(draw);
}
window.requestAnimationFrame(draw);
Sorry I didn't really edit down the code, it's just a direct copy from what I was working on. Hope it helps though.
See if this example could help you a little
Sine Wave Example canvas
function init()
{
setInterval(OnDraw, 200);
}
var time = 0;
var color = "#ff0000";
function OnDraw()
{
time = time + 0.2;
var canvas = document.getElementById("mycanvas");
var dataLine = canvas.getContext("2d");
var value = document.getElementById("lineWidth");
dataLine.clearRect(0, 0, canvas.width, canvas.height);
dataLine.beginPath();
for(cnt = -1; cnt <= canvas.width; cnt++)
{
dataLine.lineTo(cnt, canvas.height * 0.5 - (Math.random() * 2 + Math.cos(time + cnt * 0.05) * 20 ));
}
dataLine.lineWidth = value.value * 0.1;
dataLine.strokeStyle = color;
dataLine.stroke();
}
I have this code.
How I can make bounce effect as here? http://themeforest.net/item/cloud-admin-bootstrap-3-responsive-dashboard/full_screen_preview/6069264
Bounce example with a div
Change div.style.width with your canvas data..
max with the max value and the duration ..
requestAnimationframe is 60fps so 3000ms/60 gives you the number of frames.
function bounceOut(k){
return k<1/2.75?
7.5625*k*k:k<2/2.75?
7.5625*(k-=1.5/2.75)*k+.75:k<2.5/2.75?
7.5625*(k-=2.25/2.75)*k+.9375:
7.5625*(k-=2.625/2.75)*k+.984375
}
function animate(){
div.style.width=(bounceOut(current/duration)*max|0)+'px';
++current>duration||(a=webkitRequestAnimationFrame(animate));
}
var div=document.getElementsByTagName('div')[0],
duration=3000/60|0,
current=0,
max=500;
var a=webkitRequestAnimationFrame(animate);
Demo
http://jsfiddle.net/vL7Mp/1/
FULL CANVAS version
http://jsfiddle.net/vL7Mp/2/
jsut add a canvas and set the width & height
<canvas width="128" height="128"></canvas>
js
function animateC(p,C,K){
var c=C.getContext("2d"),
x=C.width/2,
r=x-(x/4),
s=(-90/180)*Math.PI,
p=p||0,
e=(((p*360|0)-90)/180)*Math.PI;
c.clearRect(0,0,C.width,C.height);
c.fillStyle=K;
c.textAlign='center';
c.font='bold '+(x/2)+'px Arial';
c.fillText(p*100|0,x,x+(x/5));
c.beginPath();
c.arc(x,x,r,s,e);
c.lineWidth=x/2;
c.strokeStyle=K;
c.stroke();
}
function bounceOut(k){
return k<1/2.75?
7.5625*k*k:k<2/2.75?
7.5625*(k-=1.5/2.75)*k+.75:k<2.5/2.75?
7.5625*(k-=2.25/2.75)*k+.9375:
7.5625*(k-=2.625/2.75)*k+.984375
}
function animate(){
animateC(bounceOut(current/duration),canvas,'rgba(127,227,127,0.3)');
++current>duration||(a=webkitRequestAnimationFrame(animate));
}
var canvas=document.getElementsByTagName('canvas')[0],
duration=6000/60|0,
current=0,
max=500,
a=webkitRequestAnimationFrame(animate);
if you have any questions just ask.
You can achieve a bounce effect by animating the draw using tweening with an easing equation.
Tween.js is a simple lib for handling this: https://github.com/sole/tween.js/
You would use it something like this:
var duration = 1000,
startValue = 0,
endValue = 100;
var tween = new TWEEN.Tween({x: startValue})
.to({ x: endValue }, duration)
.onUpdate(function() {
animate(this.x);
})
.easing(TWEEN.Easing.Bounce.Out)
.start();
Use this gist to get an easing function https://gist.github.com/dezinezync/5487119 also check out http://gizma.com/easing/
<html>
<head>
<title> two ball game</title>
</head>
<script type="text/javascript" src="jquery-1.11.3.min.js"></script>
<body>
<canvas id="canvas" width="852" height= "521" style= "border:5px solid grey ;" margin = right >
</canvas>
<script>
var x = 1;
var y = 1;
var dx = 2;
var dy = 1;
var ctx;
var WIDTH;
var HEIGHT;
init();
function circle(x,y,r) {
ctx.beginPath();
ctx.fillStyle="blue";
ctx.arc(x, y, 8, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
}
function rect(x,y,w,h) {
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
ctx.fill();
}
function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
function init() {
ctx = $('#canvas')[0].getContext("2d");
WIDTH = $("#canvas").width()
HEIGHT = $("#canvas").height()
return setInterval(draw, 10);
}
function draw() {
clear();
circle(x, y, 10);
if (x + dx > WIDTH || x + dx < 0)
dx = -dx;
if (y + dy > HEIGHT || y + dy < 0)
dy = -dy;
x += dx;
y += dy;
}
</script>
</body>
</html>
/****************************************************************\
write this code in your html