简体   繁体   English

Javascript画布

[英]Javascript Canvas

<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. 我有应该更新canvas元素和全局变量的函数,但是它们不起作用。 For instance my MoveRight function : 例如我的MoveRight函数:

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). 我希望我的MoveRight函数每次被调用时绘制一条水平线,并更新全局变量(currentx和currenty)。

you have to stroke your line! 你必须抚摸你的台词!

beginPath() will start and remeber what to draw, then stroke() to draw it. beginPath()将开始并beginPath()要绘制的内容,然后使用stroke()进行绘制。 You can then use beginPath() to clear the stroke memory so the same line isn't drawn again. 然后,您可以使用beginPath()清除笔划存储器,以便不再绘制同一行。

 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 就像@Dwadelfri所说的那样,我只想说您两次执行相同的操作

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 这样更易读,质量更好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM