html - How to move an object using X and Y coordinates in JavaScript -


i making 2-dimensional baseball game javascript , html5 , trying move image have drawn javascript so:

//canvas var c = document.getelementbyid("gamecanvas"); var ctx = c.getcontext("2d"); //baseball var baseball = new image(); baseball.onload = function() {     ctx.drawimage(baseball, 400, 425); }; baseball.src = "baseball2.png"; 

i'm not sure how move though, have seen many people seem type ballx , bally don't understand actual x , y definition comes from. here code far:

http://jsfiddle.net/xrfua/

thanks in advance @ all!

store balls position in couple of variables , can translate based on these values before drawing object, should work:

var baseballx = 0; var basebally = 0; var goleft = 0; var goright = 0; var goup = 0; var godown = 0; var ballspeed = 5;  function rendercanvas() {    // clear canvas    ctx.clearrect(0, 0, c.width, c.height);    ctx.save();     if(goleft) baseballx -= ballspeed;    if(goright) baseballx += ballspeed;    if(goup) basebally -= ballspeed;    if(godown) basebally += ballspeed;     // translate balls position    ctx.translate(baseballx, basebally);    // draw image    ctx.drawimage(baseball, 0, 0);    ctx.restore(); }  // handle user input window.addeventlistener('keyup', function(event) {    switch (event.keycode) {      case 37: // left        goleft=0;      break;      case 38: //        goup=0;      break;      case 39: // right        goright=0;      break;      case 40: // down        godown=0;      break;    }  }, false);  window.addeventlistener('keydown', function(event) {    switch (event.keycode) {      case 37: // left        goleft=1;      break;      case 38: //        goup=1;      break;      case 39: // right        goright=1;      break;      case 40: // down        godown=1;      break;    }  }, false);  // set off timer setinterval(rendercanvas,1000/100); 

here working example: fiddle


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -