<canvas id="myCanvas" width="200" height="200" style="border:1px solid #d3d3d3;"> </canvas>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var currentx;
var currenty;
currentx=0;
currenty=200;
MoveRight();
I have functions that should update the canvas element and the global variables but they are not working. For instance my MoveRight function :
function MoveRight()
{
ctx.moveTo(currentx,currenty);
ctx.lineTo(currentx+40,currenty);
currentx=currentx+40;
}
I want my MoveRight function to draw a horizontal line every time it is called and update the global variables (currentx and currenty).
you have to stroke your line!
beginPath()
will start and remeber what to draw, then stroke()
to draw it. You can then use beginPath()
to clear the stroke memory so the same line isn't drawn again.
var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); var currentx; var currenty; currentx=0; currenty=200; MoveRight(); function MoveRight() { ctx.beginPath(); ctx.moveTo(currentx,currenty); ctx.lineTo(currentx+40,currenty); currentx=currentx+40; ctx.stroke(); }
<canvas id="myCanvas" width="200" height="200" style="border:1px solid #d3d3d3;"></canvas> <button onclick="MoveRight();">Move right!</button>
its just as @Dwadelfri says, I just wanted to say that you are doing the same operation two times
ctx.lineTo(currentx+40, currenty);
currentx = currentx + 40;
can be converted to
currentx += 40;
ctx.lineTo(currentx, currenty);
it's more readable and better quality this way
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.