Animate moving an image in canvas - javascript

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

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

Canvas Background not clearing

It seems like a very simple problem and i must just be overlooking something but with this code:
window.onresize = function(){
init.canvas.width = window.innerWidth;
init.canvas.height = window.innerHeight;
}
var init = {
canvas: new Object(),
ctx: new Object(),
constructCanvas: function(){
this.canvas = document.getElementById("canvas");
this.ctx = this.canvas.getContext("2d");
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
}
}
init.constructCanvas();
var a = 20;
var b = 20;
init.ctx.lineWidth = 4;
function loop(){
init.ctx.fillStyle = "Blue";
init.ctx.fillRect(0,0,init.canvas.width,init.canvas.height);
init.ctx.moveTo(a,b);
init.ctx.lineTo(a+=9,b);
init.ctx.stroke();
}
setInterval(loop,100);
What should be happening is I get little line segments of length 9 then when the next call happens that one should clear and another line segment should be placed down at the end of the previous one but what happens instead is I just get one long line and the fillRect call seems to do nothing.
This is one of the many Canvas problems that happen if you don't use beginPath():
The canvas does get cleared properly. However you never clear the path, so you always redraw the whole line, not just the section you want. By calling moveTo and lineTo you are merely adding the next section to the already created Path, that is then drawn on stroke. You need to begin a new path instead:
function loop(){
init.ctx.fillStyle = "Blue";
init.ctx.fillRect(0,0,init.canvas.width,init.canvas.height);
init.ctx.beginPath():
init.ctx.moveTo(a,b);
init.ctx.lineTo(a+=9,b);
init.ctx.stroke();
}

trying to animate on a javascript canvas

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.

Resize a draggable fill with EaselJS

I've got a project where I'm using EaselJS to create a fill (rectangle) and text over it inside a container. My objective is to make this rectangle and text draggable to move it over the canvas. This is already done and working well.
My problem is when I try to resize the rectangle using scaleX and scaleY using a onMouseOver handler. This is indeed done, BUT the rectangle just moves away from it's initial point to some other location.
I've read I need to use the regX and regY properties to override this, but in the context of my code I just can't. What am I doing wrong?
Here's my Javascript code:
(function(){
var stage, myCanvas;
var update = true;
this.init = function() {
myCanvas = document.getElementById("stageCanvas");
stage = new createjs.Stage(myCanvas);
stage.enableMouseOver();
stage.mouseEnabled = true;
stage.mouseMoveOutside = true;
// Reference Shape
var rectFijo0 = new createjs.Shape();
rectFijo0.graphics.beginFill("#DCD8D4").rect(140,160,78,35);
stage.addChild(rectFijo0);
// Shape
var rectOpt0 = new createjs.Shape();
rectOpt0.graphics.beginFill("#C51A76").rect(140,160,78,35);
txtOpt0 = new createjs.Text("TEST","bold 20px","#FFF");
txtOpt0.textAlign ="center";
txtOpt0.x = 50;
txtOpt0.y = 50;
// Container
var containerOpt0= new createjs.Container();
containerOpt0.mouseEnabled = true;
//#######
// Probably here is my problem. I don't understand why if I use regX and regY the rectangle moves the lower right corner to the center, instead of just using this point as a registration point. Why? What I am not understanding?
//containerOpt0.regX = 78/2;
//containerOpt0.regY = 35/2;
//#######
containerOpt0.onPress = pressHandler;
containerOpt0.onMouseOver = mouseOverHandler;
containerOpt0.addChild(rectOpt0, txtOpt0);
stage.addChild(containerOpt0);
stage.update();
createjs.Ticker.setFPS(60);
createjs.Ticker.addEventListener("tick", tick);
}
function pressHandler(e){
// onPress Handler to drag
var offset = {x:e.target.x-e.stageX, y:e.target.y-e.stageY};
e.onMouseMove = function(ev) {
e.target.x = ev.stageX+offset.x;
e.target.y = ev.stageY+offset.y;
update = true;
}
}
function mouseOverHandler(e){
e.target.scaleX = .5;
e.target.scaleY = .5;
update = true;
}
function tick() {
if (update) {
update = false;
stage.update();
}
}
window.onload = init();
}());
Here's my JS Fiddle example so you can see exactly what's going on. Just drag the mouse over the rectangle to see what I mean. It must be something easy to achieve but I'm not certain how.
You issue is, that you are drawing your rects not at 0|0, the "standard" way is to draw your shape starting at 0|0 and then position the shape itself somewhere through .x and .y
rectOpt0.graphics.beginFill("#C51A76").rect(140,160,78,35);
=> changed to
rectOpt0.graphics.beginFill("#C51A76").rect(0,0,78,35);
and additionally I then placed the container at 140|160 + the regX/Y offset:
containerOpt0.regX = 78/2; //regX/Y to have is scale to the center point
containerOpt0.regY = 35/2;
containerOpt0.x = 140 + 78/2; //placement + regX offset/correction
containerOpt0.y = 160 + 35/2;
here's the updated fiddle: http://jsfiddle.net/WfMGr/2/

Image doesn't show up on canvas

I'm experimenting with the canvas element, but for some reason it doesn't display my image.
I use the following code:
function Canvas() {
this.field = function() {
var battlefield = document.getElementById('battlefield');
var canvas = battlefield.getElementsByTagName('canvas')[0];
return canvas.getContext('2d');
}
}
function Draw(canvas) {
if (!canvas) {
alert('There is no canvas available (yet)!');
return false;
}
this.canvas = canvas;
this.grass = function(pos_x, pos_y) {
var terrain = new Terrain();
var specs = terrain.grass();
var img = new Image();
img.onload = function(){
canvas.drawImage(img, specs.position_x, specs.position_y, specs.dimension_x, specs.dimension_y, pos_x, pos_y, specs.dimension_x, specs.dimension_y);
console.log('success???'); // this is being output
};
img.src = '/img/terrain.png';
}
}
(function() {
var canvas = new Canvas();
var draw = new Draw(canvas.field());
draw.grass();
})();
There are no errors, but the image just doesn't display. I've verified if the image exists and it does. I also verified the specs and they do contain what they should:
dimension_x: 25
dimension_y: 25
position_x: 0
position_y: 0
Any idea what I'm doing wrong?
http://jsfiddle.net/uwkfD/3/
pos_x and pos_y are undefined in your code. It works if you pass values for them to draw.grass():
draw.grass(0, 0);
DEMO
Tested in Chrome and Firefox.
This may be because you need a context to draw on.
Try:
this.context = canvas.getContext('2d')
Then call your draw functions on the context object not the canvas object:
this.context.drawImage(img, specs.position_x, specs.position_y, specs.dimension_x, specs.dimension_y, pos_x, pos_y, specs.dimension_x, specs.dimension_y);
It also appears that your reference to canvas is wrong too, it should be this.canvas (or this.context) not just canvas, at least as I understand scope in javascript.

Categories

Resources