Moving from setInterval method to requestAnimationFrame with sprite - javascript

I am trying to use the method 'requestAnimationFrame' with the help I can find on Internet. I can move an element, but when I want to do it with sprites, I am lost.
For example, the code below is working normally with 'setInterval', but I cannot manage to make it work with 'requestAnimationFrame'.
<!DOCTYPE html>
<html>
<head>
<title>Animating Sprites in HTML5 Canvas</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, user-scalable=no">
<style>
.demo {background: #aaaaaa;}
#myCanvas{background: #cccccc}
</style>
</head>
<body class="demo">
<canvas id="myCanvas" width="800" height="100"></canvas>
<script>
(function() {
// Canvas
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
// Set the fill style for the drawing context.
ctx.fillStyle = '#3399ff';
// VARIABLES
var width = 48; // Width CANVAS
var height = 60; // Height CANVAS
var xFrame = 0; // Frame x coordinate
var yFrame = 0; // Frame y coordinate
var dxFrame = 0; // Frame dx position in canvas
var dyFrame = 0; // Frame dy position in canvas
// SPRITE used
image = new Image()
image.src = 'myRunner2.png';
//
var requestID;
// shim layer with setTimeout fallback
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(/* function FrameRequestCallback */ callback, /* DOMElement Element */ element){
window.setTimeout(callback, 1000 / 60);
};
})();
// FUNCTION DRAWING MOVE (xFrame = 0 & yFrame = 1)
var drawMove = function(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(image, width * xFrame, height * yFrame, width, height, dxFrame, dyFrame, width, height);
if (xFrame == 7) {
xFrame = 0;
} else {
xFrame++
dxFrame+=2;
}
//window.requestAnimFrame(eMove);
}
// ANIMATION in 3 moves: Idle + Move + Tired
var intA;
function eMove() {
// Runner in motion (8 frames)
yFrame = 1;
xFrame = 0;
clearInterval(intA);
intA = setInterval(drawMove, 100);
}
eMove();
}());
</script>
</body>
</html>
I am looking for help about this issue, a portion of code will be great but a way to work or a direction to look for will be good as well. How to manipulate sprite with the method 'requestAnimationFrame'?
Ultimately, my goal is to move a sprite in one direction and the background in the other direction. I can move the sprite in one direction with setTimeout/setInterval methods alone or I can move in the other direction the background with 'requestAnimationFrame', but also separately.
I hope you understand my problem.
Thank you,
JLuc01

For requestAnimationFrame to work well it needs an accurate timer by which it can update the progress. The animation would then also depend on this variable. Of course a total duration will have to be set as well (to measure the progress). Here's a general piece of code :
var initial = update = new Date().getTime(), progress = 0, duration = 2000;
requestAnimationFrame(frameSequence);
function frameSequence() {
update = new Date().getTime();
var elapsed = update-initial;
progress = Math.max(elapsed/duration, 1);
someFunction(); // do calculations and implement them based on progress
if (progress < 1) requestAnimationFrame(frameSequence);
}
And a live example (relevant code at the bottom)
http://codepen.io/Shikkediel/pen/vEzqoX?editors=001
Edit - some comments promoted to update :
The requestAnimationFrame call is just a basic loop really to replace the timeout. It could be as simple as using requestAnimationFrame(drawMove) instead of clearInterval(intA); intA = setInterval(drawMove, 100). It'll probably do the whole thing in 8/60 of a second that way though (I see there are 8 frames and 60 is the common display refresh rate) - hence a timer would be needed.
This would optimise and work for sure : setInterval(requestAnimationFrame(drawMove), 100). It will not force a frame on the display then like a timeout does (giving performance issues and flickering) but make it wait for the first appropriate instance when there is a new paint of the screen. But not using timeouts at all is a much better approach.

Related

How do I fix my html/javascript code to animate a sprite sheet?

I attempted to animate a sprite sheet using html and javascript to no avail. Here is my sprite sheet
Below is lines 36-59 of my code. I'm not getting any errors so I don't really know what's wrong. How do I fix/improve my code?
This is for a project I'm doing. I've tried using different methods I've found online but none really worked either. I've tried shifting the image as well.
<html>
<head>
<title>Tree Animation</title>
</head>
<body>
<canvas id='canvas'></canvas>
<script>
var canWidth = 400;
var canHeight = 100;
//position where the frame will be drawn
var x = 0;
var y = 0;
var srcX;
var srcY;
var sheetWidth = 230;
var sheetHeight = 79;
var frameCount = 5;
var width = sheetWidth/frameCount;
var height;
var currentFrame = 0;
var tree = new Image();
tree.src = "tree sprite.jpg"
var canvas = document.getElementById('canvas');
canvas.width = canWidth;
canvas.height = canHeight;
var ctx = canvas.getContext('2d');
function updateFrame(){
currentFrame = ++currentFrame%frameCount
srcX = currentFrame*width;
srcY = 0;
ctx.clearRect(x, y, width, height);
}
function draw(){
updateFrame();
}
setInterval(function(){
draw();
}, 100);
</script>
</body>
</html>
I expect the output to be an animation of a tree growing, but instead I'm getting a blank page.
you should provide more code or a snippet, there are several variables didn't show up in your code
and it's hard to debug your code if u use setInterval, you should make sure your code can work first.
maybe you can try step by step:
draw the whole img on the canvas first. if it works, go next
invoke your draw() function manually, check if the img drawed
invoke more, such assetTimout(draw, 1000), check the result
ok, and i think you can console.log these variables in draw

JavaScript - how to draw on the canvas and get an image to follow the mouse

I've gotten a lot of help from this site, but I seem to be having a problem putting all of it together. Specifically, in JS, I know how to
a) draw an image onto canvas
b) make a rectangle follow the cursor (Drawing on a canvas) and (http://billmill.org/static/canvastutorial/ball.html)
c) draw a rectangle to use as a background
What I can't figure out is how to use a rectangle as the background, and then draw an image (png) on the canvas and get it to follow the cursor.
What I have so far looks like this:
var canvas = document.getElementByID('canvas');
var ctx = canvas.getContext('2d');
var WIDTH = canvas.width;
var HEIGHT = canvas.height;
var bgColor = '#FFFFFF';
var cirColor = '#000000';
clear = function() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
drawIMG = function(x,y,r) {
ctx.fillStyle = cirColor;
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
}
draw = function() {
ctx.fillStyle = bgColor;
clear();
ctx.fillRect(0, 0, WIDTH, HEIGHT);
drawIMG(150, 150, 30);
drawIMG(300, 500, 12);
};
draw();
This will draw in the HTML5 canvas element, the height and width of which are specified in the HTML and so are variable, with a white rectangle the size of the canvas beneath two black circles at (150,150) and (300,500). It does that perfectly well.
However, I don't know how to also make JS draw a .png on top of that that follows the cursor. Like I said, I've been able to do most of the steps individually, but I have no idea how to combine them. I know, for instance, that I have to do
img = new Image();
and then
img.src = 'myPic.png';
at some point. They need to be combined with position modifiers like
var xPos = pos.clientX;
var yPos = pos.clientY;
ctx.drawImage(img, xPos, yPos);
But I have no idea how to do that while maintaining any of the other things I've written above (specifically the background).
Thanks for your patience if you read through all of that. I have been up for a while and I'm afraid my brain is so fried I wouldn't recognize the answer if it stripped naked and did the Macarena. I would appreciate any help you could possibly send my way, but I think a working example would be best. I am an initiate in the religion of programming and still learn best by shamelessly copying and then modifying.
Either way, you have my optimistic thanks in advance.
First off, I've made an animated purple fire follow the mouse. Click (edit doesn't exist anymore)here to check it out.
Before you continue, I recommend you check out these websites:
http://www.williammalone.com/articles/create-html5-canvas-javascript-sprite-animation/
William talks about the basic techniques of canvas animations
http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
Paul Irish talks about a recursive animation function that turns at 60 fps.
Using both of their tutorials is pretty a good start for animation.
Now from my understanding you want one 'background' and one animation that follows the cursor. The first thing you should keep in mind is once you draw on your canvas, whatever you draw on, gets replaced. So the first thing I notice that will cause performance issues is the fact you clear your whole canvas, and not what needs to be cleared.
What you need to do is memorize the position and size of your moving element. It doesn't matter what form it takes because your clearRect() should completely remove it.
Now you're probably asking, what if I draw on the rectangle in the background. Well that will cause a problem. You have two solutions. Either, (a) Clear the background and clear your moving animation and draw them back again in the same order or (b) since you know your background will never move, create a second canvas with position = absolute , z-index = -1 , and it's location the same as the first canvas.
This way you never have to worry about the background and can focus on the animation currently going on.
Now getting back to coding part, the first thing you'll want to do is copy Paul Irish's recursive function:
(function() {
var lastTime = 0;
var vendors = ['webkit', 'moz'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame =
window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}());
Question then is, how to use it? If you go here you can check out how it was done:
function fireLoop()
{
window.requestAnimationFrame(fireLoop);
fire.update();
fire.render();
console.log('you spin me right round baby right round');
follow();
}
This is the loop I use. Every second Paul Irish's function will call the main loop. In this loop. I update the information choose the right animation that needs to be drawn and then I draw on the canvas (after having removed the previous element).
The follow function is the one that chooses the next coordinates for the animation. You'll have to change this part since, you don't want to move the canvas but move the animation. You can use the same code, but you need to apply location to where you want to draw on the canvas.
function follow()
{
$(fireCanvas).offset({
top: getTop(),
left: getLeft()
});
}
function getTop()
{
var off = $(fireCanvas).offset();
if(off.top != currentMousePos.y - $(fireCanvas).height() + 10)
{
if(off.top > currentMousePos.y - $(fireCanvas).height() + 10)
{
return off.top - 1;
}
else
{
return off.top + 1;
}
}
}
function getLeft()
{
var off = $(fireCanvas).offset();
if(off.left != currentMousePos.x - $(fireCanvas).width()/2)
{
if(off.left > currentMousePos.x - $(fireCanvas).width()/2)
{
return off.left - 1;
}
else
{
return off.left + 1;
}
}
}
var currentMousePos = { x: -1, y: -1 };
$(document).mousemove(function(event) {
currentMousePos.x = event.pageX;
currentMousePos.y = event.pageY;
});
If you want me to go into depth about anything specific let me know.

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);

Move html elements positions slow on iOS

I have a huge performance issue on iOS html5 webapp when I modify the position of multiple html elements in CSS. I would like also to move manually my elements. I do not want to use CSS transformation because it is not possible to stop the animation (we are making a highly responsive game).
My example works fine on a desktop browser (chrome, firefox, etc.), on Android. But it is very slow on an iPad 2 and an iPhone 4S (both running iOS 5.1).
Running the html5 code in a Phonegap app is better than directly in the browser but is still slow.
What do you suggest to improve things?
editable example
full screen example
First of all, if you want something that is not slow, avoid all jQuery call you can.
Here is how I would rewrite (really quickly) your code :
// shim layer with setTimeout fallback
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
var canvas = document.getElementById('canvas-test');
canvas.height = 500;
canvas.width = 500;
var context = canvas.getContext('2d');
// in this example, the fillstyle is always the same. no need to change it at every loop
context.fillStyle = "#FF0000";
var balls = [];
var ballcanvas = [];
var ballctx = [];
// create 30 balls in canvases
var eDivBody = document.getElementById('divbody');
for (var i = 0; i < 30; i++){
balls[i] = {
x : 250,
y : 100 + i * 2,
dx : 3, // direction
};
// create the canvas
var eBall = document.createElement('canvas');
eBall.id = 'ballcanvas' + i;
eBall.width = 75;
eBall.height = 75;
eDivBody.appendChild(eBall);
// some css
// no need for jQuery
eBall.style.position = "absolute";
eBall.style.left = balls[i].x + "px";
eBall.style.top = balls[i].y + "px";
eBall.style.backgroundColor = "#000000";
// associate the element to the ball, no need to go threw the DOM after
balls[i].element = eBall;
}
var ball_test = {
x : 250,
y : 300,
dx : 3 // direction
};
function loop(ball_test, balls, canvas, context, ballcanvas, ballctx){
//change of direction on the sides
if (ball_test.x > 400 || ball_test.x < 100)
ball_test.dx *= -1;
// movement
ball_test.x += ball_test.dx;
// the same for balls in canvases
// never use array.legth in a loop condition. put it in a variable then compare.
for (var i = 0, j = balls.length; i < j; i++){
// balls are following the test ball, no need to re-check the bounds
// we take the test ball direction
balls[i].dx = ball_test.dx;
//movement
balls[i].x += balls[i].dx;
// change left style - No need for jQuery
balls[i].element.style.left = balls[i].x + "px";
}
// display ball_test
displayBallTest(ball_test, canvas, context);
// Prefer the use of requestAnimationFrame
requestAnimFrame(function(){
loop(ball_test, balls, canvas, context, ballcanvas, ballctx);
});
};
// no need to recalculate Math.PI * 2 for every loop.
// do it just the first time then use the value
var pi2 = Math.PI * 2;
function displayBallTest(ball, canvas, context){
// clear canvas
// you don't need to clear all the canvas, just the zone where you now the ball is.
// must need some calculation to be the most efficient possible
context.clearRect(ball.x - 50 , ball.y - 50, 100, 100);
context.beginPath();
context.arc(ball.x, ball.y, 40, 0, pi2 );
context.fill();
};
// start main loop
loop(ball_test, balls, canvas, context, ballcanvas, ballctx);
I commented the code but here are what I did :
totally avoiding jQuery. No need, except maybe for the ready if you choose to not put your script at the end of the content
using requestAnimationFrame when possible
avoiding recalculation or reset of values when they are global
(Math.PI*2 , context.fillStyle ... )
avoiding the use of .length if for loop condition
But I think your problem come from the fact that you want to move 30 canvas elements instead of drawing theyre content into the main canvas.
iOS is known to be fast when you use Canvas Drawing.
For me, your performance problems will be resolved if you choose to draw on the main canvas instead of moving DOM elements.
One obvious thing you can do is cache your selector instead of executing it every time:
// some css
$('#ballcanvas' + i).css("position", "absolute");
$('#ballcanvas' + i).css("left", balls[i].x + "px");
$('#ballcanvas' + i).css("top", balls[i].y + "px");
$('#ballcanvas' + i).css("background-color", "#000000");
Should be something like:
var thisBall = $('#ballcanvas' + i)
thisBall.css("position", "absolute");
... rest of your code ....
Aside: Why bother using document.getElementById, when you already have Jquery $.

canvas animation javascript functions and global variables

Please, may someone help me! I am new in javascript.
I want to make canvas animation using javascript. But I have the following error
SCRIPT5007: Unable to get value of the property 'getContext': object
is null or undefined drawing_script.js, line 31 character 5
Here is the code.
Javascript:
// JScript source code
/*
Because the canvas can hold only one context at time, we'll create two canvas. Each one with its context.
One canvas for the circle, and another one for the square.
*/
var canvasCircle;
var contextCircle;
var x = 400;
var y = 300;
var dx = 2;
var WIDTH = 800;
var HEIGHT = 600;
// the circle wont make any transsformation.
function draw_circle(x, y, r) {
contextCircle.beginPath();
contextCircle.arc(x, y, r, 0, 2 * Math.PI, true);
contextCircle.closePath();
contextCircle.stroke();
}
function clear_canvas() {
contextCircle.clearRect(0, 0, WIDTH, HEIGHT);
}
function init() {
//canvasCircle = document.getElementById("canvas_circle");
canvasCircle = document.getElementById("canvas_circle");
contextCircle = canvasCircle.getContext('2d');
return setInterval(draw, 10);
}
function draw() {
// clear_canvas();
draw_circle(x, y, 50);
// if (x + dx > WIDTH || x + dx < 0)
// dx = -dx;
// x += dx;
}
init();
HTML5:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8" />
<script type="text/javascript" src="Scripts/drawing_script.js" language="javascript"></script>
<title>Blackberry</title>
</head>
<body>
<div class="drawing" style="background:Green">
<canvas id="canvas_circle" width="800" height="600"></canvas>
This is happening because your executing the script before you create the canvas.
Create the canvas element FIRST then embed the javascript.
IE: canvasCircle is undefined because you can't get an element by ID that does not exist yet!
I found the answer: the init() should be
function init() {
s_canvas = document.getElementById("canvas_square");
// Check if the canvas is supported and if the getContext is available
if (s_canvas && s_canvas.getContext) {
s_context = s_canvas.getContext("2d");
return setInterval(draw, 10);
}
else {
alert("Canvas is not supported!");
}
}
And the called of init() is replace with window.onload=init.
Since you said that you are new to javascript, I believe that the problem could be that the browser on which you are running the code may not be supporting canvas.

Categories

Resources