javascript - HTML5 Canvas y-height not correct -


so i'm trying make simple animated hmtl canvas animated block moves around canvas using wasd. noticed painting rectangle on canvas of size 5,5 made looked rectangle of size 5,10. when testing redrawing function , printing console x , y location of element in canvas, noticed rectangle can go 1-300 in x direction, 1-150 in y direction. happens though canvas styled 300,300. can figure out if i've done silly?

    <!doctype html> <html> <head>     <link rel="stylesheet" type="text/css" href="style.css">     <script type="text/javascript" src="script.js" defer></script> </head> <body>     <div class="text-holder holder" id="instruction-holder">         <p class="text" id="instruction">use wasd navigate around viewer</p>     </div>     <div class="holder" id="canvas-holder">         <canvas id="canvas"></canvas>     </div> </body> </html> 

and css

    #canvas {     width: 300px;     height:300px;     margin-left: auto;     margin-right: auto;     display: block;     border-style: solid;     border-color: grey;     border-radius: 1px; }  .holder {     display: block;     margin-left: auto;     margin-right: auto;     text-align: center; } 

and js

var = "87", down = "83", left = "65", right = "68", x = 10, y = 5, xsize = 10, ysize = 5; var c = document.getelementbyid("canvas"); var ctx = c.getcontext("2d"); var xpos, ypos;  window.addeventlistener("load",init); document.addeventlistener('keydown',move);  function init() {     xpos = 1;     ypos = 1;     ctx.fillstyle = "black";     ctx.fillrect(xpos,ypos,xsize,ysize); }  function clear() {     ctx.clearrect(0,0,300,300); }  function redraw(delx, dely) {     console.log(ypos+dely + " " + (xpos+delx));     if (xpos+delx > 0 && xpos+delx < 300 &&          ypos+dely > 0 && ypos+dely < 150) {         clear();         ctx.fillstyle = "black";         xpos = xpos+delx;         ypos = ypos+dely;         ctx.fillrect(xpos,ypos,xsize,ysize);     } }  function move(ev) {     var delx, dely;     var key = ev.keycode;     if (key == up) {         delx = 0;         dely = -y;     } else if (key == down) {         delx = 0;         dely = y;     } else if (key == left) {         delx = -x;         dely = 0;            } else if (key == right) {         delx = x;         dely = 0;     }      if (delx != undefined && dely != undefined) {         redraw(delx, dely);     } } 

you have set size of canvas explicitly or use default size of 300x150 (css scales element, not bitmap - bitmap of 300x150 stretched fit see on screen css rule, bitmap remain same size internally):

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

then remove these:

#canvas {   /* width: 300px; */   /* height:300px; */   ... 

Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -