Moving an Image Across a HTML Canvas

how to move an image on canvas html5 with arrow key press?

look a fiddle i set up:

http://jsfiddle.net/7fsw81mp/14/

function render(c){
c.clearRect(0,0,600,600)
if(fReady == true){
c.drawImage(fImage,hero.x,hero.y,100,100);
}
}

First of all I cannot see where were you calling the start function.

I put the then parameter as an external var, so i do not need to pass trought every requestAnimationFrame, i'm not sure if it goes as a parameter otherwise

Then the speed was very slow, 1 pixel per second, means that it barely moved

Also you have to clear the canvas every render, otherwise your hero will leave a trail behind him.

full snippet:

//Friend Imagevar fReady = false; var fImage = new Image();fImage.onload = function(){      fReady = true;}fImage.src="http://vignette1.wikia.nocookie.net/finalfantasy/images/0/0a/FFTS_Fighter_Sprite.png";var then = 0;//Game objectsvar hero = {     speed:10,     x:200,     y:390};
var keysDown = {};addEventListener("keydown", function(e){ keysDown[e.keyCode] = true; e.preventDefault();}, false);addEventListener("keyup", function(e){ delete keysDown[e.keyCode]; e.preventDefault();}, false);

function update(modifier){
if(38 in keysDown){ hero.y -= hero.speed * modifier; } if(40 in keysDown){ hero.y += hero.speed * modifier; } if(37 in keysDown){ hero.x -= hero.speed * modifier; } if(39 in keysDown){ hero.x += hero.speed * modifier; }}
function render(c){ c.clearRect(0,0,600,600) if(fReady == true){ c.drawImage(fImage,hero.x,hero.y,100,100); }}function setImage(){ var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); var now = Date.now(); var delta = now-then;
update(delta/1000); render(ctx);
then = now;
requestAnimationFrame(setImage);} var w = window; requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;
function start(){ console.log('starting'); then = Date.now(); setImage();}
start();
<canvas id="myCanvas" width="600" height="600"></canvas>

How to make the effect of moving the image in the window canvas?

Check out this answer: https://stackoverflow.com/a/30739547/3200577

Basically, the way that html canvas works is very different from how html elements are rendered and painted. Whereas you can select and move an html element on the page, you cannot select and move something that you have added to a canvas because all you can do on a canvas is add and clear pixels. So, when you add an image to a canvas, you are adding the pixels of the image to the canvas. If you were to add the image again but a little to the left, then it would look like you've added two images, where the second one overlaps the first, which is not what you want.

So, to animate the motion of an image on the canvas, you need to:

  • choose an x and y as the position of the image on the canvas
  • draw the image on the canvas at x and y
  • increment the values of x and y to the new position that you want
  • clear the canvas
  • redraw the image at the new x and y

A more abstract description of this flow: basically, you need to create, store, and manage your own model of what your canvas looks like; when you want to add, remove of change things that you've painted on the canvas, you actually aren't going to be adding, removing, or changing anything directly on the canvas. You would add, remove and change things in your own model, clear the canvas, and then redraw the canvas on the basis of your model.

For instance, your model might be a JS object such as

myModel = {
images: [
{ url: "my/picture.png", position: [123,556] },
{ url: "another/picture.jpg", position: [95,111] }
]
}

and you would write functions for 1) incrementing the values of the positions of the images in the model, 2) clearing the canvas, and 3) drawing your model onto the canvas. Then, you would create a loop (using requestAnimationFrame or setInterval) that would repeatedly execute those three functions.

For large or complex projects, I strongly recommend using a canvas library such as paperjs, which implements that flow for you (so that you don't have to think about creating a model and clearing and redrawing the canvas). It provides high-level functionality such as animation right out of the box.

Move image smoothly on an HTML5 canvas

The draw function displaces the image by 0.7 per 100ms. You can adjust these two parameters.

let GlassesUp = 0;var t;$('.MoveGlassesUp').on("click", function(event) {clearInterval(t)  t = setInterval(function() {    GlassesUp += 0.7;    drawMe();  }, 100);  setTimeout("clearInterval(t)", 1000)});
$('.MoveGlassesDown').on("click", function(event) {clearInterval(t) t = setInterval(function() { GlassesUp -= 0.7; drawMe(); }, 100); setTimeout("clearInterval(t)", 1000)});


var canvas = document.getElementById('cv');ctx = canvas.getContext('2d');
// core drawing functionvar drawMe = function() { var ImgGlasses = document.getElementById('glasses'); canvas.width = 400; canvas.height = 400; ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = 'red'; ctx.fillRect(0, 0, canvas.width, canvas.height); var GUp = 50;

if (GlassesUp != 0) {
GUp = GUp - GlassesUp; //alert(GUp) }
ctx.drawImage(ImgGlasses, 0, 0, 250, 250, 50, GUp, 250, 250);





}

drawMe();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<button class="MoveGlasses MoveGlassesUp">up</button><button class="MoveGlasses MoveGlassesDown">down</button><hr/><canvas id="cv"></canvas>
<img src="https://image.flaticon.com/icons/svg/126/126514.svg" style="height:60px;width:100px;opacity:0" id="glasses" />

Move cropped image in HTML5 canvas

You should create the shape at your desired location in the first place, that would be the appropriate solution.

However, at this stage, you can use getImageData() and putImageData() methods to accomplish the movements ...

// Grab the Canvas and Drawing Contextvar canvas = document.getElementById('c');var ctx = canvas.getContext('2d');
// Create an image elementvar img = document.createElement('IMG');
// When the image is loaded, draw itimg.onload = function() {
// Save the state, so we can undo the clipping ctx.save();
// Create a shape, of some sort ctx.beginPath(); ctx.moveTo(10, 10); ctx.lineTo(100, 30); ctx.lineTo(180, 10); ctx.lineTo(200, 60); ctx.arcTo(180, 70, 120, 0, 10); ctx.lineTo(200, 180); ctx.lineTo(100, 150); ctx.lineTo(70, 180); ctx.lineTo(20, 130); ctx.lineTo(50, 70); ctx.closePath(); // Clip to the current path ctx.clip();
ctx.drawImage(img, 0, 0);
// Undo the clipping ctx.restore(); move(50, 100); //move left: 50px, down: 100px}
// Set cross origin for the image, as it's not hosted on local serverimg.crossOrigin = 'anonymous';
// Specify the src to load the imageimg.src = "http://i.imgur.com/gwlPu.jpg";
function move(left, down) { var croppedImage = ctx.getImageData(0, 0, 200, 200); ctx.clearRect(0, 0, canvas.width, canvas.height); //clear canvas ctx.putImageData(croppedImage, 0 + left, 0 + down);}
canvas {   background: #CEF;}
<canvas id="c" width="400" height="400"></canvas>

Moving an image on a javascript canvas

Problem is that your [x,y] values are undefined in your draw function.

Demo: http://jsfiddle.net/m1erickson/qAm39/

Here's a refactoring of your code to keep things in proper scope:

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
body{ background-color: ivory; }
#canvas{border:1px solid red;}
</style>

<script>
$(function(){


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"),
cx = canvas.getContext("2d");

function Card(x,y){
this.x = x || 0;
this.y = y || 0;
this.img=new Image();

this.init=function(){

// "var self=this" makes myCard available in the img.onload function
// otherwise "this" inside img.onload refers to the img
var self=this;

this.img.onload = function()
{
self.draw();
loop();
}
this.img.src = "https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house16x16.png";
}

// x,y need to be this.x and this.y

this.draw = function(){
cx.drawImage(this.img, this.x, this.y);
}

}

var myCard = new Card(50,50);
myCard.init();

function loop(){

if(myCard.x<canvas.width-20){
requestAnimFrame(loop);
}

cx.clearRect(0, 0, canvas.width, canvas.height);

myCard.x++;

myCard.draw();

}


}); // end $(function(){});
</script>

</head>

<body>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

Move different images across a canvas on a timer/delay

You expressed interest in having code do the following:

  • Preload all images.
  • Move images across the canvas.
  • Use an animation loop function so code is not repeated.
  • Use requestAnimationFrame instead of setTimeout for efficiency.

Here's example code and a Demo:

var canvas=document.getElementById("canvas");var ctx=canvas.getContext("2d");var cw=canvas.width;var ch=canvas.height;

var images=[];images.push({x:20,y:200,moveX:5,maxX:250,delay:100,nextTime:0,url:'https://dl.dropboxusercontent.com/u/139992952/multple/cars1.png'});images.push({x:20,y:30,moveX:10,maxX:100,delay:500,nextTime:0,url:'https://dl.dropboxusercontent.com/u/139992952/multple/sun.png'});var imageCount=images.length;for(var n=0;n<images.length;n++){ var i=images[n]; i.img=new Image(); i.img.onload=start; i.img.src=i.url;}function start(){ if(--imageCount>0){return;} requestAnimationFrame(animate);}

function animate(time){ requestAnimationFrame(animate); var needsRedrawing=false; for(var n=0;n<images.length;n++){ var i=images[n]; if(time>i.nextTime){ if(i.x+i.moveX<i.maxX){ i.x+=i.moveX; i.nextTime+=i.delay; needsRedrawing=true; } } } if(needsRedrawing){ ctx.clearRect(0,0,cw,ch); for(var n=0;n<images.length;n++){ var i=images[n]; ctx.drawImage(i.img,i.x,i.y); } }}
body{ background-color: ivory; padding:10px; }#canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>


Related Topics



Leave a reply



Submit