I have this :
http://jsfiddle.net/geduardcatalin/6Lg6ymt3/
How can I make the second line to start from center and stop at the bottom left corner like the first one is stoping where I want ( in the center ) ?
var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); var canvasWidth = canvas.width; var canvasHeight = canvas.height; var i = 0; var j = 0; var k = 0; var l = 0; function drawLine1() { i = i + 1; j = j + 1; x1 = i; y1 = j; if (i >= 149) { i = 149; } if (j >= 149) { j = 149; } ctx.beginPath(); ctx.strokeStyle = "#000000"; ctx.lineWidth = 1; ctx.moveTo(0, 0); ctx.lineTo(x1, y1); ctx.stroke(); } function drawLine2() { k = k - 1; l = l + 1; x2 = k; y2 = l; if (k >= 299) { k = 299; } if (l >= 299) { l = 299; } ctx.beginPath(); ctx.strokeStyle = "#000000"; ctx.lineWidth = 1; ctx.moveTo(150, 150); ctx.lineTo(x2, y2); ctx.stroke(); } function drawLines() { ctx.clearRect(0, 0, canvasWidth, canvasHeight); drawLine1(); drawLine2(); //setTimeout(drawLine2, 0000); } setInterval(drawLines, 40);
* { margin: 0; padding: 0; } html { background-color: #555555; } #wrapper { width: 300px; height: 300px; margin: 70px auto; border: 1px solid red; }
<div id="wrapper"> <canvas id="myCanvas" height="300px" width="300px"></canvas> <p id="demo"></p> </div>
The variable k
and l
in the Line2 should both start at 150, and change draw Line2()
to this:
Here is the updated JSFiddle .
function drawLine2(){
k = k - 1;
l = l + 1;
x2 = k;
y2 = l;
if ( k <= 0 ){
k = 0;
}
if ( l >= 299 ){
l = 299;
}
ctx.beginPath();
ctx.strokeStyle = "#000000";
ctx.lineWidth = 1;
ctx.moveTo(150, 150);
ctx.lineTo(x2, y2);
ctx.stroke();
}
This is because your l
variable is stopping at 299
but k
goes on forever. k
is going from 0
to -299
(and not 0
to 299
), so to fix it you want to change it's condition to:
if ( k <= -299 ){
k = -299;
}
And have the correct ctx.lineTo(x2 + 149, y2 + 149);
you mentioned in your comment.
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.