0
<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).

1
  • canvas is inside the html tags and the functions are inside the <script> </script>. Commented Feb 2, 2017 at 21:19

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.