trying to animate on a javascript canvas - javascript

as the title said i'm trying to animate on a java canvas but i'm not sure how to add on to the vector class of my objects current position
I've been told to use this:
Bus.prototype.update = function()
{
this.getPosition().add(new Vector(10.0));
}
but it doesn't recognize the .add function and comes up with an error when i use my setInterval function
I'll include my get/set functions aswell just incase
Bus.prototype.getPosition = function() {
return this.mPosition;
};
Bus.prototype.setPosition = function (pPosition) {
this.mPosition = pPosition;
};
I'm pretty new at coding so i apologize if this is very vague or badly written

jsFiddle : https://jsfiddle.net/CanvasCode/41z9o10p/1/
javascript
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var Bear = function(xSet, ySet)
{
this.XPos = xSet;
this.YPos = ySet;
}
Bear.prototype.updatePosition = function(xValue, yValue)
{
this.XPos += xValue;
this.YPos += yValue;
}
var bear = new Bear(0,0);
setInterval( function()
{
ctx.fillStyle = "#000";
ctx.fillRect(0,0,c.width,c.height);
ctx.fillStyle = "#0F0";
ctx.fillRect(bear.XPos, bear.YPos, 50,50);
bear.updatePosition(0.2, 0.4);
} ,1);
Bear is a custom "class". All bear has is a X position and a Y position, the constructor can take in two values which will set the X and Y value. I then add a new method to Bear which is called updatePosition. All updatePosition does it take in two values and add them to the original X position and Y position (you can also provide negative numbers to move the opposite way). Now with our Bear we can create one and then use its updatePosition function and move it.

Related

Animate moving an image in canvas

Im new to using canvas but wonder if i could get some help or advice on where to start with this. i currently have a circle drawn on canvas and have tried multiple ways i thought might work but cant get my head round it. When searching online i can only really find help where the shapes are drawn in canvas itself.
Here is what i have so far: JSFiddle
JavaScript:
var one = document.getElementById("canvOne");
var canvOne = one.getContext("2d");
var img = new Image();
img.onload = function(){
canvOne.drawImage(img, 10, 10);
};
img.src = "img/circle.jpg";
function oneStart(){
for(var i = 0; i < 300; i++){
img.style.left = i + 'px';
setTimeout(oneStart, 1000);
}
};
can anyone give me a hand with this please?
jsFiddle : http://jsfiddle.net/8eLL7L5L/3/
javascript
//canvas one
var one = document.getElementById("canvOne");
var canvOne = one.getContext("2d");
var img = new Image();
var animate = false;
var circlePosX = 10;
var circlePosY = 10;
img.onload = function () {
canvOne.drawImage(img, circlePosX, circlePosY);
};
img.src = "http://www.alexvolley.co.uk/other/circle.jpg";
var start = function()
{
animate = true;
}
var stop = function()
{
animate = false;
}
setInterval(function () {
// Only update circle position if animate is true
if (animate) {
circlePosX += 1;
canvOne.fillStyle = "#FFF";
canvOne.fillRect(0, 0, one.width, one.height);
canvOne.drawImage(img, circlePosX, circlePosY);
}
}, 3);
All I have done is created 3 variables and added a few little functions, the circle's XPos and YPos are now stored so we can access them, I have also created a bool variable animate which is used to check if we should animate the circle.
The start function simply sets animate to true
The stop function simple sets animate to false
the setInterval just keeps running the same code over and over every 3 miliseconds, all this does is clears the canvas and then redraws the circle. If we don't clear the canvas you would see multiple circles appear when animate is true.
I hope this helped

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.

get global var of mousemove and update onFrame event in paper.js

I am new to Paper.js therefore might this a basic question but I am trying to the the following:
var xpos;
var ypos;
function onMouseMove(event) {
xpos = event.point.x;
ypos = event.point.y;
}
get the current mouseposition and save it as the variables xpos and ypos
function onFrame(event) {
path.segments[1].point.x = path.segments[1].point.x+xpos/10;
path.segments[1].point.y = path.segments[1].point.y+ypos/10;
}
and then use them to update the onFrame animation. But it does not work, how can I update the animation with the new values?
Thanks in advance.
It looks like your code is increasing the position of path.segments[1] every frame. I believe what you want is to subtract a portion of the difference between the segment and mouse positions per frame.
Try this:
var path = new Path.Line((0,0), view.center);
path.strokeColor = "black";
var pos = new Point(0, 0);
function onMouseMove(event) {
pos = event.point;
}
function onFrame(event) {
path.segments[1].point += (pos - path.segments[1].point) / 10;
}

Collision with Chipmunk JS failing

http://videobin.org/+70a/8wi.html
You can see what's happening there, and a demo to try it here: http://student.dei.uc.pt/~drgomes/carry/index.html.
So, I'm using Chipmunk JS demos to get an idea of how it works (see https://github.com/josephg/Chipmunk-js). The simple demo starts alright but then things start jumping crazily and I've been trying to figure out this with no luck so far.
var radToDeg = 180 / Math.PI;
function PlayState() {
this.blocks = [];
this.setup = function() {
space.iterations = 100;
space.gravity = new cp.Vect(0, 150);
space.game = this;
this.ground = space.addShape(new cp.SegmentShape(space.staticBody, new cp.v(0, 480), new cp.v(640, 480), 0));
this.ground.setElasticity(0);
this.ground.setFriction(1);
};
this.update = function() {
space.step(this.dt);
for (var i = 0; i < this.blocks.length; i++) {
var block = this.blocks[i];
block.sprite.x = block.body.p.x;
block.sprite.y = block.body.p.y;
block.sprite.angle = block.body.a * radToDeg;
}
if (isMouseDown("left")) {
if (this.canAddBlock) {
this.canAddBlock = false;
this.addBlock(mouseX, mouseY);
}
} else {
this.canAddBlock = true;
}
};
this.draw = function() {
clearCanvas();
for (var i = 0; i < this.blocks.length; i++) {
this.blocks[i].sprite.draw();
}
// this.ground.sprite.draw();
};
this.addBlock = function(x, y) {
width = 64;
height = 64;
var newBlock = new Block(x, y, width, height);
newBlock.body = space.addBody(new cp.Body(1, cp.momentForBox(1, width, height)));
newBlock.body.setPos(new cp.v(x, y));
newBlock.shape = space.addShape(new cp.BoxShape(newBlock.body, width, height));
newBlock.shape.setElasticity(0);
newBlock.shape.setFriction(1);
this.blocks.push(newBlock);
};
}
desiredFPS = 60;
switchState(new PlayState());
The source code is pretty straightforward, I have my doubts about the way I'm creating the ground since I can't really tell in what position it actually is. The cubes seem to find it and collide against it though.
The other source file is a little Block class to help me organize things:
Block = (function() {
function constructor(x, y, width, height) {
this.sprite = new Sprite("res/block.png", x, y);
this.width = width;
this.height = height;
}
constructor.prototype = {
update: function() {
}
};
return constructor;
})();
From watching the behavior, I think it is as simple as the sprites and the chipmunk bodies not rotating around the same point. I believe chipmunk rotations are around the center of mass. It looks like the sprites are rotating around the upper left corner. In fact, they may be drawing from that corner too, which explains why they stack funny, and intersect the bottom plane.
I think you need something like this in the update function. (pseudocode):
offset = Vector(-width/2,-height/2)
offset.rotate_by(block.body.a)
block.sprite.x = block.body.p.x + offset.x
block.sprite.y = block.body.p.y + offset.y
I don't know chipmunk at all but playing around with your demo it seems like the Physics isn't right at all (right from the beginning for me). Just a hunch from looking at your code, but it looks to me like you should be setting the dimensions on the Sprite instance in your Block class, rather than on the Block instance itself.
Block = (function() {
function constructor(x, y, width, height) {
this.sprite = new Sprite("res/block.png", x, y);
// Do you mean to set the width and height of the sprite?
this.sprite.width = width;
this.sprite.height = height;
}
constructor.prototype = {
update: function() {
}
};
return constructor;
})();

Clear entire, transformed HTML5 Canvas while preserving context transform

I want to zoom and pan an HTML5 Canvas by transforming the context using translate() and scale(), clearing the canvas, and then redrawing. Note that I am explicitly not calling save() and restore() around my transformations.
If I perform the standard ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height) then the entire visible canvas will not be cleared; downscaling or panning may cause this initial rectangle to not exactly cover the drawing area.
If I perform the Webkit-friendly clearing method...
var w=canvas.width;
canvas.width = 0;
canvas.width = w;
...then the cumulative transformation of the context is reset.
How can I best clear the entire canvas context without losing my transformation?
Keeping track of all the transformation information like you are presumably doing is what several others so far have done (like cake.js and my own library, for two). I think doing this will pretty much be an inevitability for any large canvas library.
Ilmari of cake.js even complained to mozilla:
https://bugzilla.mozilla.org/show_bug.cgi?id=408804
You could instead call save/restore around your clear method:
// I have lots of transforms right now
ctx.save();
ctx.setTransform(1,0,0,1,0,0);
// Will always clear the right space
ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
ctx.restore();
// Still have my old transforms
Won't that satisfy your case?
For those who care to track their full context transforms, here's my code for doing so in an on-demand, per-context basis. This is prefaced with the usage that shows how to clear the full rectangle based on the transformed coordinates. You can see the code in use on my website.
window.onload = function(){
var canvas = document.getElementsByTagName('canvas')[0];
var ctx = canvas.getContext('2d');
trackTransforms(ctx);
function redraw(){
var p1 = ctx.transformedPoint(0,0);
var p2 = ctx.transformedPoint(canvas.width,canvas.height);
ctx.clearRect(p1.x,p1.y,p2.x-p1.x,p2.y-p1.y);
// ...
}
}
// Adds ctx.getTransform(), returning an SVGMatrix
// Adds ctx.transformedPoint(x,y), returning an SVGPoint
function trackTransforms(ctx){
var svg = document.createElementNS("http://www.w3.org/2000/svg",'svg');
var xform = svg.createSVGMatrix();
ctx.getTransform = function(){ return xform; };
var savedTransforms = [];
var save = ctx.save;
ctx.save = function(){
savedTransforms.push(xform.translate(0,0));
return save.call(ctx);
};
var restore = ctx.restore;
ctx.restore = function(){
xform = savedTransforms.pop();
return restore.call(ctx);
};
var scale = ctx.scale;
ctx.scale = function(sx,sy){
xform = xform.scaleNonUniform(sx,sy);
return scale.call(ctx,sx,sy);
};
var rotate = ctx.rotate;
ctx.rotate = function(radians){
xform = xform.rotate(radians*180/Math.PI);
return rotate.call(ctx,radians);
};
var translate = ctx.translate;
ctx.translate = function(dx,dy){
xform = xform.translate(dx,dy);
return translate.call(ctx,dx,dy);
};
var transform = ctx.transform;
ctx.transform = function(a,b,c,d,e,f){
var m2 = svg.createSVGMatrix();
m2.a=a; m2.b=b; m2.c=c; m2.d=d; m2.e=e; m2.f=f;
xform = xform.multiply(m2);
return transform.call(ctx,a,b,c,d,e,f);
};
var setTransform = ctx.setTransform;
ctx.setTransform = function(a,b,c,d,e,f){
xform.a = a;
xform.b = b;
xform.c = c;
xform.d = d;
xform.e = e;
xform.f = f;
return setTransform.call(ctx,a,b,c,d,e,f);
};
var pt = svg.createSVGPoint();
ctx.transformedPoint = function(x,y){
pt.x=x; pt.y=y;
return pt.matrixTransform(xform.inverse());
}
}

Categories

Resources