gpt4 book ai didi

javascript - 为什么我的 Canvas 线条不是单独绘制的?

转载 作者:行者123 更新时间:2023-12-03 10:28:47 25 4
gpt4 key购买 nike

我的 Canvas 上有一些动画线,它们不是单独绘制的,而是试图绘制为一条完整的路径。为什么会发生这种情况?

$(document).ready(function(){
canvas = document.getElementById("test");
ctx = canvas.getContext("2d");

function animateLines(name, x1, y1, x2, y2, stroke, width, duration){
var count = 0;
var ms = 10;
duration = duration * ms;

ctx.beginPath();
ctx.moveTo(x1, y1);

function countNumbers(){
count += 1;
if(x2 > x1){
ctx.lineTo((x1 + count), y2);
}

else if(y2 > y1){
ctx.lineTo(x1, (y1 + count));
}

if((x1 < x2) && (count == x2)){
clearInterval(counter);
}

else if((y1 < y2) && (count == y2)){
clearInterval(counter);
}
ctx.lineWidth = width;
ctx.strokeStyle = stroke;
ctx.stroke();
}

$("#pause").on("click", function(){
clearInterval(counter);
})
$("#play").on("click", function(){
counter = setInterval(countNumbers, duration);
})
}

animateLines("Line", 0, 100, 100, 100, "white", 5, 3);
//animateLines("Line2", 150, 250, 350, 250, "red", 5, 5);
//animateLines("Line3", 100, 0, 100, 300, "blue", 5, 1);
})

当我只调用该函数一次时,它工作得很好,当我多次调用它时,它会尝试绘制一个完整的形状。

最佳答案

您需要moveTo(x1, x2)对于每一行,也到 beginPath()为了改变他们的描边颜色:否则,stroke()将绘制所有形状。

var canvas = document.getElementById("test"),
ctx = canvas.getContext("2d");

function animateLines(name, x1, y1, x2, y2, stroke, width, duration) {
var count = 0;
var ms = 10;
duration = duration * ms;
var counter;


function countNumbers() {
ctx.beginPath();
ctx.moveTo(x1, y1);

count += 1;
if (x2 > x1) {
ctx.lineTo((x1 + count), y2);
} else if (y2 > y1) {
ctx.lineTo(x1, (y1 + count));
}

if ((x1 < x2) && (count == x2)) {
clearInterval(counter);
} else if ((y1 < y2) && (count == y2)) {
clearInterval(counter);
}
ctx.lineWidth = width;
ctx.strokeStyle = stroke;

ctx.stroke();
}

$("#pause").on("click", function() {
clearInterval(counter);
})
$("#play").on("click", function() {
counter = setInterval(countNumbers, duration);
})
}

animateLines("Line", 0, 100, 100, 100, "green", 5, 3);
animateLines("Line2", 150, 250, 350, 250, "red", 5, 5);
animateLines("Line3", 100, 0, 100, 300, "blue", 5, 1);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<button id="pause">Pause</button>
<button id="play">play</button></div>
<canvas id="test" width="350" height="350"></canvas>

关于javascript - 为什么我的 Canvas 线条不是单独绘制的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29305220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com