I'm trying to get an image to oscillate. But i'm having some issues. I'm using this tutorial http://www.html5canvastutorials.com/advanced/html5-canvas-oscillation-animation/
and I tried changing line 55-61 of the tutorial to load the image src. But it's not displaying anything.
Any advice?
<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
function drawRectangle(myRectangle, context) {
context.beginPath();
context.rect(myRectangle.x, myRectangle.y, myRectangle.width, myRectangle.height);
context.fillStyle = '#8ED6FF';
context.fill();
context.lineWidth = myRectangle.borderWidth;
context.strokeStyle = 'black';
context.stroke();
}
function animate(myRectangle, canvas, context, startTime) {
// update
var time = (new Date()).getTime() - startTime;
var amplitude = 150;
// in ms
var period = 2000;
var centerX = canvas.width / 2 - myRectangle.width / 2;
var nextX = amplitude * Math.sin(time * 2 * Math.PI / period) + centerX;
myRectangle.x = nextX;
// clear
context.clearRect(0, 0, canvas.width, canvas.height);
// draw
drawRectangle(myRectangle, context);
// request new frame
requestAnimFrame(function() {
animate(myRectangle, canvas, context, startTime);
});
}
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var myRectangle = new Image();
myRectangle.src = "http://www.skilledsoldiers.com/e107_plugins/aacgc_gamelist/icons/dota2_icon.png";
myRectangle.onload = function()
};
drawRectangle(myRectangle, context);
// wait one second before starting animation
setTimeout(function() {
var startTime = (new Date()).getTime();
animate(myRectangle, canvas, context, startTime);
}, 1000);
</script>
You need to use context.drawImage instead of trying to draw a rectangle with an image.
function drawImage(myRectangle, context) {
context.drawImage(myRectangle.img, myRectangle.x, myRectangle.y, myRectangle.width, myRectangle.height);
}
See this fiddle: http://jsfiddle.net/fb4vS/
Related
I am trying to make the images race each other and once one of the images passes the finish line display the winner.
I have some old code I used for the animation but i don't know how to implement the images with it.
<html>
<head>
<title>Canvas Race</title>
<script src="jquery-2.2.3.js"></script>
<style type="text/css">
canvas {
border: 1px solid black;
background-image: url("http://www.gamefromscratch.com/image.axd?picture=road2048v2.png");
background-size: 200px 300px;
background-position-y: -81px;
}
</style>
</head>
<body>
<canvas id="canvas" width="1100" height="150" >
<script>
var blueCar = new Image();
var redCar = new Image();
// images
function image(){
blueCar.src = "http://worldartsme.com/images/car-top-view clipart-1.jpg";
redCar.src = "http://images.clipartpanda.com/car-clipart-top-view-free-vector-red-racing-car-top-view_099252_Red_racing_car_top_view.png";
}
window.onload = function draw(){
var ctx = document.getElementById('canvas').getContext('2d');
ctx.globalCompositeOperation = 'destination-over';
window.requestAnimationFrame(draw);
window.requestAnimationFrame(animate);
// finish line
ctx.beginPath();
ctx.moveTo(1020, 150);
ctx.lineTo(1020, 0);
ctx.strokeStyle = "#FFEF0E";
ctx.stroke();
//blue car
ctx.save();
if(blueCar.complete){
ctx.drawImage(blueCar, 10, 10, 100, 60);
}
// red car
if(redCar.complete){
ctx.drawImage(redCar, 10, 80, 100, 60);
}
}
image();
</script>
</canvas>
<div id="winner"></div>
</body>
</html>
Old code:
I want to use this old code but i don't know what to remove and how to add the images that i have above for the cars. As you can see for this code i created squares instead of images.
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
// drawing red square
function drawRedRect(redCar, ctx) {
ctx.beginPath();
ctx.drawImage(redCar, 5, 5);
}
// finish line
function drawFinishLine(ctx){
ctx.beginPath();
ctx.moveTo(1040, 150);
ctx.lineTo(1040, 0);
ctx.stroke();
}
// this is drawing the blue square
function drawBlueRect(blueRectangle, ctx){
ctx.beginPath();
ctx.rect(blueRectangle.x, blueRectangle.y, blueRectangle.width, blueRectangle.height);
ctx.fillStyle = 'blue';
ctx.fill();
}
// red square animation
function animate(lastTime, redCar, blueRectangle, runAnimation, canvas, ctx) {
if(runAnimation.value) {
// update
var time = (new Date()).getTime();
var timeDiff = time - lastTime;
// pixels / second
var redSpeed = Math.floor((Math.random() * 400) + 1);
var blueSpeed = Math.floor((Math.random() * 400) + 1);
var linearDistEachFrameRed = redSpeed * timeDiff / 1000;
var linearDistEachFrameBlue = blueSpeed * timeDiff / 1000;
var currentX = redRectangle.x;
var currentZ = blueRectangle.x;
if(currentX < canvas.width - redRectangle.width - redRectangle.borderWidth / 2) {
var newX = currentX + linearDistEachFrameRed;
redRectangle.x = newX;
}
if(currentZ < canvas.width - blueRectangle.width - blueRectangle.borderWidth / 2) {
var newZ = currentZ + linearDistEachFrameBlue;
blueRectangle.x = newZ;
}
console.log(redSpeed);
console.log(blueSpeed);
// clear
ctx.clearRect(0, 0, canvas.width, canvas.height);
// draw
drawFinishLine(ctx);
drawRedRect(redRectangle, ctx);
drawBlueRect(blueRectangle, ctx);
//winner(win);
// request new frame
requestAnimFrame(function() {
animate(time, redRectangle, blueRectangle, runAnimation, canvas, ctx);
});
}
}
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var win = document.getElementById('Winner')
//blue square
var blueRectangle = {
x: 5, y: 30, width: 45, height: 25, borderWidth:5
};
//red square
var redRectangle = {
x: 5,
y: 90,
width: 45,
height: 25,
borderWidth: 5
};
/!*
* define the runAnimation boolean as an obect
* so that it can be modified by reference
*!/
var runAnimation = {
value: false
};
// add click listener to canvas
document.getElementById('myCanvas').addEventListener('click', function() {
// flip flag
runAnimation.value = !runAnimation.value;
if(runAnimation.value) {
var date = new Date();
var time = date.getTime();
animate(time, redRectangle, blueRectangle, runAnimation, canvas, ctx);
}
});
drawFinishLine(ctx);
drawRedRect(redRectangle, ctx);
drawBlueRect(blueRectangle, ctx);
//winner(win);
Here is some of your code refactored to race car images:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
// game vars
var redRectangle={x:5,y:40,width:62,height:21};
var goldRectangle={x:5,y:75,width:62,height:21};
var finishX=450;
// animation vars
var nextTime=0;
var delay=1000/60;
// image vars and call start() when all images are loaded
var red=new Image();
red.onload=start;
red.src='https://dl.dropboxusercontent.com/u/139992952/multple/car1.png';
var gold=new Image();
gold.onload=start;
gold.src='https://dl.dropboxusercontent.com/u/139992952/multple/car2.png';
var imageCount=2;
function start(){
// return if all the images aren't loaded
if(--imageCount>0){return;}
// start the animation loop
requestAnimationFrame(animate);
}
function animate(time){
// has the desired time elapsed?
if(time<nextTime){requestAnimationFrame(animate);return;}
nextTime=time+delay;
// update the car positions
redRectangle.x+=Math.random()*5;
goldRectangle.x+=Math.random()*5;
// draw the current scene
ctx.clearRect(0,0,canvas.width,canvas.height);
drawFinishLine(ctx);
drawRedRect(redRectangle, ctx);
drawgoldRect(goldRectangle, ctx);
// request another animation loop
hasRedWon=redRectangle.x+redRectangle.width>finishX;
hasGoldWon=goldRectangle.x+goldRectangle.width>finishX;
// alert if race is over
if(hasRedWon){ alert('Red wins'); return; }
if(hasGoldWon){ alert('Gold wins'); return; }
// race is still going, request another animation loop
requestAnimationFrame(animate);
}
// draw images instead of rects
function drawRedRect(redRectangle, ctx){
ctx.drawImage(red, redRectangle.x, redRectangle.y, redRectangle.width, redRectangle.height);
}
// draw images instead of rects
function drawgoldRect(goldRectangle, ctx){
ctx.drawImage(gold, goldRectangle.x, goldRectangle.y, goldRectangle.width, goldRectangle.height);
}
// draw finish line
function drawFinishLine(){
ctx.fillRect(finishX,0,5,ch);
}
body{ background-color: ivory; }
#canvas{border:1px solid red; }
<canvas id="canvas" width=500 height=300></canvas>
I do not understand the code highlighted below that has a comment "I DO NOT UNDERSTAND WHAT IS GOING ON HERE". I know it is a call back function. But I do not understand how the function operates and the purpose. For the record I understand everything else. I have never seen a function written like this before. I do understand that the OR statements are for detecting which browser.
<body>
<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
window.requestAnimFrame = (function(callback) {
// I DO NOT UNDERSTAND WHAT IS GOING ON HERE
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
console.log("inside callback");
window.setTimeout(callback, 1000 / 60);
};
})();
function drawRectangle(myRectangle, context) {
context.beginPath();
context.rect(myRectangle.x, myRectangle.y, myRectangle.width, myRectangle.height);
context.fillStyle = '#8ED6FF';
context.fill();
context.lineWidth = myRectangle.borderWidth;
context.strokeStyle = 'black';
context.stroke();
}
function animate(myRectangle, canvas, context, startTime) {
// update
var time = (new Date()).getTime() - startTime;
var linearSpeed = 100;
// pixels / second
var newX = linearSpeed * time / 1000;
if(newX < canvas.width - myRectangle.width - myRectangle.borderWidth / 2) {
myRectangle.x = newX;
}
// clear
context.clearRect(0, 0, canvas.width, canvas.height);
drawRectangle(myRectangle, context);
// request new frame
requestAnimFrame(function() {
animate(myRectangle, canvas, context, startTime);
});
}
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
//
var myRectangle = {
//position
x: 0,
y: 75,
//dimension
width: 100,
height: 50,
// stlye
borderWidth: 5
};
drawRectangle(myRectangle, context);
// wait one second before starting animation
setTimeout(function() {
var startTime = (new Date()).getTime();
animate(myRectangle, canvas, context, startTime);
}, 1000);
</script>
When you OR two values together with JavaScript, you don't explicitly get a boolean... you get back the first truthy value. This is often used to provide defaults or fallbacks. For example:
console.log( null || 'some string'); // Logs 'some string'
var myOption = 'some value';
myOption = myOption || 'default value'; // myOption is 'some value'
What's happening specifically in your code is that the function requestAnimationFrame took a long time to be standardized. Each browser vendor made their own version of it with their own prefix. This function is going through each possible name of that function until it hits one. (A function is "truthy" where undefined or null is not.)
I tried to make some simply game using requestAnimFrame but animation doesn't work and I don't know why. Maybe some one can help? Here is the code:
// requestAnimationFrame() shim by Paul Irish
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(/* function */ callback, /* DOMElement */ element){
window.setTimeout(callback, 1000 / 60);
};
})();
//Create canvas
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 640;
canvas.height = 480;
document.body.appendChild(canvas);
// The main game loop
var lastTime;
function main() {
var now = Date.now();
var dt = now - lastTime;
draw();
update(dt);
lastTime = now;
requestAnimFrame(main);
}
main();
function ball(){
this.radius = 5;
this.x = 300;
this.y = 50;
this.vx = 200;
this.vy = 200;
this.ax = 0;
this.ay = 0;
this.color = "red";
this.draw = function(){
ctx.beginPath();
ctx.fillStyle = this.color;
ctx.arc( this.x, this.y, this.radius, 0, 2 * Math.PI );
ctx.fill();
};
}
function draw() {
newBall = new ball();
newBall.draw();
}
function update(dt) {
newBall = new ball();
newBall.x += newBall.vx * dt;
}
In update(dt) function ball dosen't move and I don't know why...
There are several errors in your code:
You're initializing variables outside of a function, always use an initializer (immediately invoked function) for that.
As mentioned by kalley you are creating a new ball at the starting position for every draw instead of using a global object.
Even if your ball would draw correctly it would be outside the drawing area within the next frame because Date.now() is measured in seconds (use .getMilliseconds()).
Lastly the ball stays at the same position because the canvas isn't cleaned up after each draw.
what you're looking for:
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
theBall.draw();
}
There are several other things but this fiddle should do for now.
Trying to double the size of a circle onclick(). Doesn't seem to be working?
HTML
<canvas id="drawing" width="600px" height="600px" onclick="resize()"></canvas>
Javascript
window.onload = function() {
canvas=document.getElementById("drawing");
context=canvas.getContext("2d");
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 70;
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill();
}
function resize () {
context.fillStyle= "#701be0"; // This changes the rectangle to blue
context.fill();
context.scale(10.5, 2.5);
}
You need to redraw your circle again and also keep in mind that context.scale() will also scale its position so i wouldn't recommend to do it this way. You can just draw a new circle over with bigger radius.
jsFiddle - http://jsfiddle.net/DSFMq/
Here's a jsFiddle for exactly what I needed, in case anyone needs help.
http://jsfiddle.net/elijahmurray/fHv82/1/
x=200;
y=200;
size=100;
radius=30;
function animate() {
reqAnimFrame = window.mozRequestAnimationFrame || //get framerate
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame
;
reqAnimFrame(animate);
if(radius <= 200) {
radius +=3;
} //increase size by 1 per frame
draw();
}
function draw() {
var canvas = document.getElementById("ex1");
var context = canvas.getContext("2d");
context.beginPath();
context.arc(x, y, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill();
}
animate();
This script is endlessly taking memory in all the browsers. I can't see why!
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var particles = [], amount = 5;
var x = 100; var y = 100;
var W, H;
var p, gradient;
//dimensions
if(window.innerHeight){
W = window.innerWidth, H = window.innerHeight;
}else{
W = document.documentElement.clientWidth, H = document.documentElement.clientHeight;
}
canvas.width = W, canvas.height = H;
//array voor de meerdere particles
for(var i=0;i<amount;i++){
particles.push(new create_particle());
}
function create_particle(){
//random positie op canvas
this.x = Math.random()*W;
this.y = Math.random()*H;
//random snelheid
this.vx = Math.random()*20-10;
this.vy = Math.random()*20-10;
//Random kleur
var r = Math.random()*255>>0;
var g = Math.random()*255>>0;
var b = Math.random()*255>>0;
this.color = "rgba("+r+", "+g+", "+b+", 0.5)";
this.radius = Math.random()*20+20;
}
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
function draw(){
canvas.width = canvas.width;
canvas.height = canvas.height;
//achtergrond tekenen
//ctx.globalCompositeOperation = "source-over";
//ctx.fillStyle = "rgba(0,0,0,0.5)";
ctx.fillRect(0, 0, W, H);
//ctx.globalCompositeOperation = "lighter";
//teken cirkel
for(var t=0; t<particles.length;t++){
p = particles[t];
//gradient
gradient = ctx.createRadialGradient(p.x,p.y,0,p.x,p.y,p.radius);
gradient.addColorStop(0,"white");
gradient.addColorStop(0.4,"white");
gradient.addColorStop(0.4,p.color);
gradient.addColorStop(1,"black");
ctx.beginPath();
ctx.fillStyle = gradient;
ctx.arc(p.x,p.y,p.radius,Math.PI*2,false)
ctx.fill();
//beweeg
p.x+=p.vx;
p.y+=p.vy;
//canvas boundery detect
if(p.x < -50)p.x = W+50;
if(p.y < -50)p.y=H+50;
if(p.x > W+50)p.x = -50;
if(p.y > H+50)p.y = -50;
}
}
(function animloop(){
canvas.width = canvas.width;
canvas.height = canvas.height;
requestAnimFrame(animloop);
draw();
})();
//resize?
function resizeCanvas(){
canvas.height = W;
canvas.width = H;
ctx.fillRect(0, 0, W, H);
}
if(window.addEventListener){
window.addEventListener('resize', resizeCanvas, false);
}else{
window.attachEvent('resize', resizeCanvas);
}
I tried to change some code around (this is also final version) but still it leaks. If you use this script and watch 'taskmanager' or in-browser's memory check you see that it slowly and constantly eats memory.
EDIT: after adding in the canvas.height solution and moving some declaring's around, the script still leaks! I must say that it looks like Firefox leaks harder then Chrome!
You have:
canvas.width = canvas.width;
canvas.height = canvas.height;
I'm guessing this does the same as clearRect... but to be sure try this too:
function draw(){
ctx.clearRect ( 0 , 0 , canvas.width , canvas.height );
/* draw */
}
See if any thing changes.
Try cleaning the canvas before starting another set of drawing. You can clear it by setting it's width and height again.
Here is some orientative code:
function draw() {
canvas.width = canvas.width;
canvas.height = canvas.height;
/* draw */
}
my guess is your create_particle function could be leaking but im not sure as how, one idea would be to create an interal object instead of using this
function create_particle(){
return {
x: Math.random()*W,
y: Math.random()*H,
vx: Math.random()*20-10,
vy: Math.random()*20-10,
r: Math.random()*255>>0,
g: Math.random()*255>>0,
b: Math.random()*255>>0,
color: "rgba("+r+", "+g+", "+b+", 0.5)",
radius: Math.random()*20+20,
};
}
Im not sure if this is the issue, but it seems to be the only thing I can really think of that kinda looks odd,