html - How to move image on canvas using arrow keys in javascript -
i've tried few different ways have seen on here, can't quite image move. whenever try adapting code arrow key presses, seems make canvas shrink , player model (spaceperson) disappear.
here "drawing board" keep returning to, , have far.
// canvas , context var canvas = document.getelementbyid("space"); var ctx = canvas.getcontext("2d"); canvas.width = 1920; canvas.height = 700; // create image object var spaceperson = new image(); // add onload event handler spaceperson.onload = function () { // done loading, can use image ctx.drawimage(spaceperson, 280, 300); }; // artwork harrison marley (using make8bitart.com) spaceperson.src = "http://i.imgur.com/eh9dpq2.png";`
i quite new javascript, , trying work out how can move specperson image using arrow keys. trying make class space person access x,y values, can't seem draw image without using .onload
here more complete example:
//just utility function image(url, callback){ var img = new image(); if(typeof callback === "function"){ img.onload = function(){ //just ensure callback executed async settimeout(function(){ callback(img, url) }, 0) } } img.src = url; return img; } //a utility keep value constrained between min , max function clamp(v, min, max){ return v > min? v < max? v: max: min; } //returns function can called keycode or 1 of known aliases //and returns true||false wether button down var iskeydown = (function(aliases){ for(var i=256, keydown=array(i); i--; )keydown[i]=false; var handler = function(e){ keydown[e.keycode] = e.type === "keydown"; e.preventdefault(); //scrolling; if have suppress }; addeventlistener("keydown", handler, false); addeventlistener("keyup", handler, false); return function(key){ return(true === keydown[ key in aliases? aliases[ key ]: key ]) } })({ //some aliases, extended up: 38, down: 40, left: 37, right: 39 }); // canvas , context var canvas = document.getelementbyid("space"); canvas.width = 1920; canvas.height = 700; var ctx = canvas.getcontext("2d"); //the acutal image little-part of defines figue var spaceperson = { image: image("//i.imgur.com/eh9dpq2.png", function(img){ spaceperson.width = img.naturalwidth; spaceperson.height = img.naturalheight; //start rendering calling update update(); }), //position x: 60, y: 310, width: 0, height: 0, speed: 200 // 200px/s }; var lastcall = 0; //to calculate (real) time between 2 update-calls //the render-fucntion function update(){ //taking account (sometimes changing) framerates var = date.now(), time = lastcall|0 && (now-lastcall)/1000; lastcall = now; requestanimationframe(update); var sp = spaceperson, speed = sp.speed; //checking pressed buttons , calculates direction //two opposite buttons cancel out each other, left , right var dx = (iskeydown('right') - iskeydown('left')) * time, dy = (iskeydown('down') - iskeydown('up')) * time; //fix speed diagonals if(dx && dy) speed *= 0.7071067811865475; // * 1 / math.sqrt(2) if(dx) { //there movement on x-axes sp.x = clamp( //calculate new x-position //currentpos + direction * speed sp.x + dx * sp.speed, //restraining result bounds of map 0, canvas.width - sp.width ); } //same y if(dy) sp.y = clamp(sp.y + dy * sp.speed, 0, canvas.height - sp.height); ctx.clearrect(0, 0, canvas.width, canvas.height); ctx.drawimage(sp.image, sp.x, sp.y); }
edit:
a quick question (i hope); if later add other objects, check collisions in update()?
this still basic example. main purpose of update()
-function should work main event-loop. trigger events have happen each frame in order have happen.
var lastcall = 0; function update(){ //i want next frame requestanimationframe(update); //handle timing var = date.now(), //time since last call in seconds //cause it's easier think in //tems 50px/s 0.05px/ms or 0.8333px/frame time = lastcall|0 && (now-lastcall) / 1000; lastcall = now; moveplayer(time); moveenemies(time); movebullets(time); collisiondetection(); render(); } function render(){ ctx.clear(0, 0, canvas.width, canvas.height); drawbackground(ctx); for(var i=0; i<enemies.length; ++i) enemies[i].render(ctx); player.render(ctx); }
not saying have implement these functions now, give idea of possible structure. don't scared break big tasks (functions) subtasks.
, might make sense give each enemy move()
-function can implement different movement-patterns per enemy, or pattern (and be) same each enemy, parameterized @ best, can handle in loop.
same thing rendering, i'm showing in last part of code.
Comments
Post a Comment