我正在尝试在canvas元素中逐步绘制线条(目前使用递归函数),并且我能够成功地绘制与x或y轴平行的线对,这样:
function line(xa, ya, xb, yb) {
context.beginPath();
context.moveTo(xa, ya);
context.lineTo(xb, yb);
context.stroke();
}
(function drawLine(i){
line(155, i, 155, i-2);
line(245, i, 245, i-2);
if (i > 35) {
setTimeout(function(){
drawLine(i-2);
}, 10);
}
})(57);
我明白了:
(context.lineWidth
设置为10
,context.lineCap
设置为round
)
然而,我已经尝试了几种方法来绘制不是严格水平或垂直的线对,但我只能得到这样的东西:
(function drawLine(i){
line(155, i, 155+(57-i)/2, i-2);
line(245, i, 245-(57-i)/2, i-2);
if (i > 35) {
setTimeout(function(){
drawLine(i-2);
}, 10);
}
})(57);
(更改context.lineWidth
或context.lineCap
的值无法解决问题)
有没有办法在canvas元素中逐步绘制任何类型的线?
答案 0 :(得分:1)
在第一个版本中,您可以根据i
的当前值从一个点绘制线条,并在下一次迭代中根据i
的值绘制一条点。但在第二个版本中,起点的x
值是常量。将起点定位在i
上,将终点定位在i - 2
上:
let c = document.querySelector('canvas');
let context = c.getContext('2d');
context.lineWidth = 10;
context.lineCap = 'round';
function line(xa, ya, xb, yb) {
context.beginPath();
context.moveTo(xa, ya);
context.lineTo(xb, yb);
context.stroke();
}
(function drawLine(i){
line(155 + (57 - i) / 2, i, 155 + (57 - (i - 2)) / 2, (i - 2));
line(245 - (57 - i) / 2, i, 245 - (57 - (i - 2)) / 2, (i - 2));
if (i > 35) {
setTimeout(function(){
drawLine(i-2);
}, 10);
}
})(57);

<canvas></canvas>
&#13;
答案 1 :(得分:0)
最简单的方法是使用Canvas.js:
const canvas = new Canvas('my-canvas', 200, 200).start();
const line1 = new Canvas.Line({
from: {
x: 50,
y: 70
},
to: {
x: 60,
y: 30
},
lineWidth: 7,
lineCap: 'round',
lineLength: 0.1
});
canvas.addElement(line1);
line1.animate('lineLength', {lineLength: 1, duration: 500});
const line2 = new Canvas.Line({
from: {
x: 90,
y: 70
},
to: {
x: 80,
y: 30
},
lineWidth: 7,
lineCap: 'round',
lineLength: 0.1
});
canvas.addElement(line2);
line2.animate('lineLength', {lineLength: 1, duration: 500});
&#13;
<script src="https://gustavgenberg.github.io/handy-front-end/Canvas.js"></script>
&#13;
答案 2 :(得分:0)
沿任何路径设置动画的简单方法是使用直线和线划线偏移。
const ctx = canvas.getContext('2d');
ctx.lineWidth = 10;
ctx.lineCap = 'round';
function drawLines(){
function drawLine(x1, y1, x2, y2){
ctx.moveTo(x1,y1);
ctx.lineTo(x2,y2);
}
drawLine(10,10,490,90);
drawLine(10,190,490,110);
}
var lineLength = 30; // pixels
var distanceBetween = 400;
var lineSpeed = 300; //pixels per second
ctx.setLineDash([lineLength, distanceBetween]);
function animateLines(time){
ctx.lineDashOffset = -time * lineSpeed / 1000;
ctx.stroke();
}
function loop(time){
ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
ctx.beginPath();
drawLines();
animateLines(time);
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
<canvas id="canvas" width=500 height=200></canvas>