繁体   English   中英

如何使用画布逐步绘制任何线条

[英]How to progressively draw any line using Canvas

我正在尝试在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设置为10context.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.lineWidthcontext.lineCap的值不能解决问题)

有没有一种方法可以在canvas元素中逐渐绘制任何类型的线条?

在你的第一个版本,您基于当前值的点画线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> 

最简单的方法是使用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}); 
 <script src="https://gustavgenberg.github.io/handy-front-end/Canvas.js"></script> 

使用破折号沿路径设置动画。

沿任何路径设置动画的简单方法是使用虚线和虚线偏移量。

 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> 

暂无
暂无

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

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