Html5 canvas animation. How to reset rectangle when it hits the end - javascript

Hey Im experimenting with some html5 animation and so far I have a square that "falls" whenever I press the button. I was wondering how i could have it go back to the top when it hits the bottom and fall again.
My current code is:
<html>
<head>
</head>
<body>
<canvas id="myCanvas" width="200" height="400" style="border:1px solid black;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
function draw (x,y){
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.save();
var side = 10
var up = 10
ctx.clearRect(0,0,200,400);
ctx.fillStyle = "#FF0000";
ctx.fillRect(x,y,up,side);
ctx.restore();
y += 5;
var loopTimer = setTimeout('draw('+x+','+y+')',30);
}
</script>
<button onclick="draw(0,0)">draw</button>
</body>
</html>

Using your variables y, you can simply check if it is below the height of the canvas height.
if( y > c.height ){ // use the canvas height, not the context height
y = 0;
}
Also, the way you're currently calling the timer is a bit inefficient. Instead of :
var loopTimer = setTimeout('draw('+x+','+y+')',30);
I would recommend
var loopTimer = setTimeout(function(){ draw(x,y); },30);
Here's a working example: http://jsfiddle.net/vwcdpLvv/

Related

Circle not appearing over image in html 5

I am trying to add a circle over the image and I am using the .onload function too but the circle is still being drawn below the image.
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="1024" height="500" style="border:1px solid #d3d3d3;">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var background = new Image();
background.src = "https://i.imgur.com/ua7gL3M.png";
// Make sure the image is loaded first otherwise nothing will draw.
background.onload = function(){
ctx.drawImage(background,0,0);
}
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.arc(512,200,60,0,2*Math.PI);
ctx.strokeStyle = "red"
ctx.lineWidth = 5;
ctx.stroke();
</script>
</body>
</html>
When I run the code snippet, there's a brief moment the circle is visible before the image is rendered. The image has to wait to load before it is rendered, but the circle is being drawn immediately. Because of that, the circle is drawn first then the image is placed on top of it. To fix this, you can draw the circle after the image is rendered. See this revised code snippet:
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="1024" height="500" style="border:1px solid #d3d3d3;">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var background = new Image();
background.src = "https://i.imgur.com/ua7gL3M.png";
// Make sure the image is loaded first otherwise nothing will draw.
background.onload = function(){
ctx.drawImage(background,0,0);
// The following lines were moved into the onload callback
ctx.beginPath();
ctx.arc(512,200,60,0,2*Math.PI);
ctx.strokeStyle = "red"
ctx.lineWidth = 5;
ctx.stroke();
}
var ctx = canvas.getContext("2d");
</script>
</body>
</html>

js getContext stops further code from executing

I have a working getContext in my JavaScript code, but for some reason nothing is executed after this method. Here, I added two alerts and only one of them runs:
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas"
width="0"
height="0"
style="border:5px solid #888888; fill: solid #DDDDDD;"
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
// basic vars
var squareDim = 25;
var screenWidth = 10;
var screenHeight = 20;
// setting up the canvas
var canvas = document.getElementById("myCanvas");
canvas.width = screenWidth * squareDim;
canvas.height = screenHeight * squareDim;
alert(1)
var ctx = c.getContext("2d");
alert(2);
// draw a single square
function putSquare(color, x, y) {
ctx.fillStyle = color;
ctx.fillRect(x * squareDim, y * squareDim, squareDim, squareDim);
}
for (i=0; i<screenHeight; i++) {
putSquare("#FF0000", i, 0);
}
</script>
</body>
Does anyone have an idea where did I screw up?
You're calling c.getContext(...), you have no c variable declared - you need to call this on canvas instead:
var ctx = canvas.getContext('2d');
In future you can debug things like this in your browser's JavaScript console. In your JavaScript console, you'll see that your code here is throwing the following error:
Uncaught ReferenceError: c is not defined
See: How to open the JavaScript console in different browsers?

Rotate text in a canvas with javascript

In the following code i want to rotate the text of each element of the array in javascript. If i use for example ctx.rotate(Math.PI/10) before the filltext, it rotates all the elements. The positioning of the text also changes with ctx.rotate(Math.PI/10) and if i use 90 degrees, ctx.rotate(Math.PI/2) the text does not show on the canvas.
<html>
<canvas id="myCanvas" width="300" height="300" style="border:1px solid #d3d3d3;"></canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var x = new Array("Day1","Day2","Day3","Day4","Day5");
ctx.rotate(Math.PI/10);
for(var i = 0; i < x.length; i++){
ctx.fillText(x[i],i*50+20,50);
}
</script>
</html>
As i said, i want to rotate each element on its own and with that the positioning of each element should stay the same as in the non-rotated text as in the code above. Thus each element has to rotate around its own axis. How can i achieve this?
Have made some changes in your code, it should help:
<html>
<canvas id="myCanvas" width="300" height="300" style="border:1px solid
#d3d3d3;"></canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var x = new Array("Day1","Day2","Day3","Day4","Day5");
for(var i = 0; i < x.length; i++){
var size = ctx.measureText(x[i]);
ctx.save();
var tx = (i*50+20) + (size.width/2);
var ty = (50);
ctx.translate(tx,ty);
ctx.rotate(Math.PI / 10);
ctx.translate(-tx,-ty);
ctx.fillText(x[i],i*50+20,50);
ctx.restore();
}
</script>
</html>
Demo: http://jsfiddle.net/m1erickson/YyN2P/
A brief overview:
context.translate to where you want the rotation point of the text
context.rotate
context.fillText with an X offset == 1/2 the text width and Y offset == 1/2 the text height
(you can context.measureText to measure the text width)
wrap all this in context.save and context.restore.
use requestAnimationFrame to drive your animation.
And some example code:
var word1="Day1";
var word1Width=ctx.measureText(word1).width;
var r=0;
animate();
function animate(){
requestAnimationFrame(animate);
r+=Math.PI/180;
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.save();
ctx.translate(100,100);
ctx.rotate(r);
ctx.fillText(word1,-word1Width/2,4);
ctx.restore();
}

html5 canvas context .fillStyle not working

Just giving canvas a go for the first time with the intention of creating a game. I have an image displaying but oddly the fillStyle method doesn't seem to be working. ( At least the canvas background is still white in google chrome.)
Note that in my code the canvas var is actually the canvas elements 2d context, maybe that's where i'm getting myself confused? i can't see the problem, would appreciate if anyone else could.
LD24.js:
const FPS = 30;
var canvasWidth = 0;
var canvasHeight = 0;
var xPos = 0;
var yPos = 0;
var smiley = new Image();
smiley.src = "http://javascript-tutorials.googlecode.com/files/jsplatformer1-smiley.jpg";
var canvas = null;
window.onload = init; //set init function to be called onload
function init(){
canvasWidth = document.getElementById('canvas').width;
canvasHeight = document.getElementById('canvas').height;
canvas = document.getElementById('canvas').getContext('2d');
setInterval(function(){
update();
draw();
}, 1000/FPS);
}
function update(){
}
function draw()
{
canvas.clearRect(0,0,canvasWidth,canvasHeight);
canvas.fillStyle = "#FFAA33"; //orange fill
canvas.drawImage(smiley, xPos, yPos);
}
LD24.html:
<html>
<head>
<script language="javascript" type="text/javascript" src="LD24.js"></script>
</head>
<body>
<canvas id="canvas" width="800" height="600">
<p> Your browser does not support the canvas element needed to play this game :(</p>
</canvas>
</body>
</html>
3 notes:
fillStyle does not cause your canvas to be filled. It means that when you fill a shape it will be filled with that color. Therefore you need to write canvas.fillRect( xPos, yPos, width, height).
Wait until your image actually loads, otherwise the rendering may be inconsistent or buggy.
Careful of cross-domain images used in your canvas - most browsers will throw a security exception and stop executing your code.
Wait till image loads as well:
var img = new Image();
img.onload = function() {
handleLoadedTexture(img);
};
img.src = "image.png";
function handleLoadedTexture(img) {
//call loop etc that uses image
};
Or maybe you were just missing
canvas.fill();
after
canvas.drawImage(smiley, xPos, yPos);

Image is flickering continuously in pressing button?

The Image is flickering as I continuously push the button. The problem might be in ctx.clearRect(0,0,100,500) . How can I resolve the problem?
I am trying to animate in HTML 5 canvas.
I need a moving object in canvas and when I push the button, the other moving object follow the previous without flickering.
function draw(x,y){
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.save();
ctx.clearRect(0,0,100,500); // This may be the problem
var img=document.getElementById("Image");
ctx.drawImage(img,50,y);
ctx.restore();
y -= 10;
var loopTimer = setTimeout('draw('+x+','+y+')',50);
}
HTML 5
<button onclick="draw(0,500)">Draw</button>
<canvas id="canvas" width="600" height="500">
</canvas>
It looks like the problem may be because you aren't clearing the entire canvas. Try this:
function draw(x,y){
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.save();
ctx.clearRect(0,0, canvas.width, canvas.height);
var img=document.getElementById("Image");
ctx.drawImage(img,50,y);
ctx.restore();
y -= 10;
var loopTimer = setTimeout('draw('+x+','+y+')',50);
}
Demo
The image flicker when you press the button more than once, which means you start the setTimeout() more than once. Add a variable to check if it's already been pressed.

Categories

Resources