簡體   English   中英

html畫布動畫曲線

[英]html canvas animate curve lines

我使用canvas quadraticCurveTo相互連接創建了一些線條。 我的目標是為這些線條制作動畫。 我有一個使用lineTo方法的例子,如何為quadraticCurveTo方法更改它?

(function () {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
    window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
    window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'];
}

if (!window.requestAnimationFrame) window.requestAnimationFrame = function (callback, element) {
    var currTime = new Date().getTime();
    var timeToCall = Math.max(0, 16 - (currTime - lastTime));
    var id = window.setTimeout(function () {
        callback(currTime + timeToCall);
    },
    timeToCall);
    lastTime = currTime + timeToCall;
    return id;
};

示例鏈接: http//jsfiddle.net/m1erickson/7faRQ/

我的期望: 示例圖片

沿着路徑的動畫

要作為小提琴,但使用任何路徑功能,您可以使用線破折號來設置繪制的路徑的數量。 這將為您提供沿着恆定速度的路徑的動畫。

這種方法唯一的問題是你不知道路徑有多長。 要知道這涉及一些相當復雜的數學(警告一些貝塞爾長度解決方案是近似值)。

在這個例子中,我用眼睛來計算長度。

 requestAnimationFrame(loop); const ctx = canvas.getContext("2d"); ctx.lineCap = "round"; const lines = [[10, 10], [300, 10, 250, 200], [100, 300, 20, 120, 10, 10]]; const render = { "2"(p) { ctx.lineTo(...p) }, "4"(p) { ctx.quadraticCurveTo(...p) }, "6"(p) { ctx.bezierCurveTo(...p) }, start(width, col) { ctx.lineWidth = width; ctx.strokeStyle = col; ctx.beginPath() } } var startTime; const len = 760; function loop(time) { if(startTime === undefined){ startTime = time } const animTime = time - startTime; ctx.clearRect(0, 0, 300, 300); ctx.setLineDash([1, 0]); render.start(1,"blue") lines.forEach(l => render[l.length](l)); ctx.stroke(); ctx.setLineDash([(animTime / 10) % len, 10000]); render.start(8, "red") lines.forEach(l => render[l.length](l)); ctx.stroke(); requestAnimationFrame(loop); } 
 canvas { border : 2px solid black; } 
 <canvas id="canvas" width = 300 height = 300></canvas> 

我知道這個問題有點陳舊,但是對於這個問題的變化,SO充滿了錯誤的答案,直到我發現這個問題,我找不到好的解決方案。 @ Blindman67用setLineDash向我指出了正確的方向,以下對我來說非常有效。 rnd2()返回范圍內的隨機整數(但你總是可以使用常量或參數),而curves()計算其曲線的快速粗略近似長度(和弦和總段長度的平均值),其中I乘以1.2,以確保我不會過去。 我的setLineDash調用與alpha <1.0一起使用,因為它不會反復過度繪制曲線,並且它不會花費額外的時間來計算長不可見的空白。 raf()是requestAnimationFrame。

var lineLen = 0, delta = rnd2(20, 80);
var approxCurveLen = curves(c0.width, c0.height, ctx, false) * 1.2;
var step = () =>
{
    if (lineLen < approxCurveLen)
    {
        ctx.setLineDash([0, lineLen, delta, approxCurveLen-lineLen]);
        ctx.stroke();
        lineLen += delta;
        raf(step);
    }
    else
    {
        ctx.setLineDash([]);
    }
};
raf(step);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM