javascript - HTML5 Canvas 斐波那契螺旋线

标签 javascript jquery html math canvas

目前我正在查看这段代码,但无法找出问题所在。

 function fibNumbers() {
    return [0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
}

function continiusFib(a) {
    var b = fibNumbers(),
    c = Math.floor(a),
    d = Math.ceil(a);
    if (d >= b.length)
        return null;
    a = Math.pow(a - c, 1.15);
    return b[c] + (b[d] - b[c]) * a
}

function drawSpiral(pointA, pointB) {
    var b = pointA;
    var c = pointB;
    ctx.translate(b.x, b.y);
    b = Math.sqrt(((c.x - b.x) * (c.x - b.x)) + ((c.y - b.y) * (c.y - b.y)));
    d = 1 / Math.sqrt(((c.x - b.x) * (c.x - b.x)) + ((c.y - b.y) * (c.y - b.y)));
    c = Math.acos(c.x - b.x);
    0 > Math.asin(c.y - b.y) && (c = 2 * Math.PI - c);
    ctx.rotate(c);
    ctx.scale(b / 5, b / 5);
    var d = Math.PI / 100;
    ctx.moveTo(0, 0);
    for (var e = 0; e < 50 * (fibNumbers().length - 1) ; e++) {
        var f = e * d, g = continiusFib(e / 50),
        h = Math.cos(f) * g,
        f = Math.sin(f) * g;
        ctx.lineTo(h, f);
    }
    ctx.scale(5 / b, 5 / b);
    ctx.rotate(-c);
    //ctx.stroke();
}

我想画的是不同于黄金螺旋的斐波那契螺旋

我也有这个question供其他引用。 enter image description here

enter image description here

最佳答案

我是这样做的。要做的事情是找到从点 A 到 B 的 Angular 处的螺旋半径,然后缩放螺旋以适合。

该函数在 Canvas 上呈现以点 A 为中心并与点 B 相交的螺旋线。它使用 ctx.setTransform 来定位螺旋以适应约束,或者您可以只使用比例和中心偏移来转换螺旋点并保持默认的 Canvas 转换(以防您正在绘制其他东西);

注意事项

  • 如果 pointB === pointA 没有解,则不绘制。
  • 如果 pointA 离 Canvas 太远,可能无法绘制(我没有 对此进行了测试)。
  • 总是从中心向外画。不考虑裁剪 螺旋而不是停止的地方。

所以代码。 (更新)

// Assume ctx is canvas 2D Context and ready to render to
var cx = ctx.canvas.width / 2;
var cy = ctx.canvas.height / 2;
var font = "Verdana";       // font for annotation
var fontSize = 12;          // font size for annotation
var angleWind = 0;
var lastAng;

function getScale(){ // gets the current transform scale
    // assumes transform is square. ie Y and X scale are equal and at right angles
    var a = ctx.currentTransform.a;  // get x vector from current trans
    var b = ctx.currentTransform.b;
    return Math.sqrt(a * a + b * b);  // work out the scale    
}

// Code is just a quicky to annotate line and aid visualising current problem
// Not meant for anything but this example. Only Tested on Chrome
// This is needed as the canvas text API can not handle text at very small scales
// so need to draw at unit scale over existing transformation
function annotateLine(pA, pB, text, colour, where){  
    var scale, size, ang, xdx, xdy, len, textStart, ox, oy;

    scale = getScale(); // get the current scale
    size = fontSize;  // get font size

    // use scale to create new origin at start of line
    ox = ctx.currentTransform.e + pA.x * scale ;
    oy = ctx.currentTransform.f + pA.y * scale;

    // get direction of the line
    ang = Math.atan2(pB.y - pA.y, pB.x - pA.x);
    xdx = Math.cos(ang); // get the new x vector for transform
    xdy = Math.sin(ang);

    // get the length of the new line to do annotation positioning
    len = Math.sqrt( Math.pow(pB.y - pA.y, 2) + Math.pow(pB.x - pA.x, 2) ) * scale;

    ctx.save();  // save current state

    //Set the unit scaled transform to render in
    ctx.setTransform(xdx, xdy, -xdy, xdx, ox, oy); 

    // set fint
    ctx.font= size + "px " + font;

    // set start pos
    textStart = 0;
    where = where.toLowerCase();  // Because I can never get the cap right
    if(where.indexOf("start") > -1){
        textStart = 0;  // redundent I know but done
    }else
    if(where.indexOf("center") > -1 || where.indexOf("centre") > -1 ){ // both spellings 
        // get the size of text and calculate where it should start to be centred
        textStart = (len - ctx.measureText(text).width) / 2;
    }else{
        textStart = (len - ctx.measureText(text).width);
    }
    if(where.indexOf("below") > -1){  // check if below
        size = -size * 2;
    }
    // draw the text
    ctx.fillStyle = colour;
    ctx.fillText(text, textStart,-size / 2);    

    ctx.restore(); // recall saved state


}

// Just draws a circle and should be self exlainatory 
function circle(pA, size, colour1, colour2){
    size = size * 1 / getScale();
    ctx.strokeStyle = colour1;
    ctx.fillStyle = colour2;
    ctx.beginPath();
    ctx.arc(pA.x, pA.y, size , 0, Math.PI * 2);
    ctx.fill();
    ctx.stroke();
}

function renderSpiral(pointA, pointB, turns){
    var dx, dy, rad, i, ang, cx, cy, dist, a, c, angleStep, numberTurns, nTFPB, scale, styles, pA, pB;
    // clear the canvas
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

    // spiral stuff
    c = 1.358456;   // constant See https://en.wikipedia.org/wiki/Golden_spiral
    angleStep = Math.PI/20;  // set the angular resultion for drawing
    numberTurns = 6;  // total half turns drawn

    nTFPB = 0;   //  numberOfTurnsForPointB is the number of turns to point
                     // B should be integer and describes the number off
                     // turns made befor reaching point B

    // get the ang from pointA to B
    ang = (Math.atan2(pointB.y - pointA.y, pointB.x - pointA.x) + Math.PI * 2) % (Math.PI *2 );

    // Check for winding. If the angle crosses 2PI boundary from last call
    // then wind up or wind down the number of turns made to get to current
    // solution.
    if(lastAng !== undefined){
        if(lastAng > Math.PI * 1.5 && ang < Math.PI * 0.5 ){
            angleWind += 1;
        }else
        if(lastAng < Math.PI * 0.5 && ang > Math.PI * 1.5 ){
            if(angleWind > 0){
                angleWind -= 1;
            }
        }
    }
    lastAng = ang;  // save last angle

    // Add the windings
    nTFPB += angleWind;

    // get the distance from A to B
    dist = Math.sqrt(Math.pow(pointB.y-pointA.y,2)+Math.pow((pointB.x)-pointA.x,2));
    if(dist === 0){
        return;  // this makes no sense so exit as nothing to draw
    }
    // get the spiral radius at point B
    rad = Math.pow(c,ang + nTFPB * 2 * Math.PI); // spiral radius at point2

    // now just need to get the correct scale so the spiral fist to the
    // constraints required.
    scale = dist / rad;

    while(Math.pow(c,Math.PI*numberTurns)*scale < ctx.canvas.width){
        numberTurns += 2;
    }

    // set the scale, and origin to centre
    ctx.setTransform(scale, 0, 0, scale, pointA.x, pointA.y);

    // make it look nice create some line styles
    styles = [{
            colour:"black",
            width:6
        },{
            colour:"gold",
            width:5
        }
    ];

    // Now draw the spiral. draw it for each style 
    styles.forEach( function(style) {
        ctx.strokeStyle = style.colour;
        ctx.lineWidth = style.width * ( 1 / scale); // because it is scaled invert the scale
                                                    // can calculate the width required
        // ready to draw                               
        ctx.beginPath();
        for( i = 0; i <= Math.PI *numberTurns; i+= angleStep){
            dx = Math.cos(i);  // get the vector for angle i
            dy = Math.sin(i);
            var rad = Math.pow(c, i);  // calculate the radius
            if(i === 0) {                
                ctx.moveTo(dx * rad , dy * rad );        // start at center
            }else{
                ctx.lineTo(dx * rad , dy * rad );  // add line
            }
        }
        ctx.stroke();  // draw it all
    });

    // first just draw the line A-B
    ctx.strokeStyle = "black";
    ctx.lineWidth = 2 * ( 1 / scale); // because it is scaled invert the scale
                                      // can calculate the width required

    // some code to help me work this out. Having hard time visualising solution                                      
    pA = {x: 0, y: 0};                                      
    pB = {x: 1, y: 0};                                      
    pB.x = ( pointB.x - pointA.x ) * ( 1 / scale );
    pB.y = ( pointB.y - pointA.y ) * ( 1 / scale );
    // ready to draw                               
    ctx.beginPath();
    ctx.moveTo( pA.x, pA.y );        // start at center
    ctx.lineTo( pB.x, pB.y );  // add line
    ctx.stroke();  // draw it all

    if(scale > 10){
        ctx.strokeStyle = "blue";
        ctx.lineWidth = 1 * ( 1 / scale); 
        ctx.beginPath();
        ctx.moveTo( 0, 0 );        // start at center
        ctx.lineTo( 1, 0 );  // add line
        ctx.stroke();  // draw it all
    }

    annotateLine(pA, pB, "" + ((ang + angleWind * Math.PI * 2) / Math.PI).toFixed(2) + "π", "black", "centre");
    annotateLine(pA, pB, "" + rad.toFixed(2), "black", "centre below");

    if(scale > 10){
        annotateLine({x: 0, y: 0}, {x: 1, y: 0}, "1 Unit", "blue", "centre");
    }

    circle(pA, 5, "black", "white");
    circle(pB, 5, "black", "white");

    ctx.setTransform(1,0,0,1,0,0); // reset transform to default;
}

var centerMove = 0;
canvasMouseCallBack = function(){
    centerMove += 0.0;
    renderSpiral(
        {
            x:cx+Math.sin(centerMove)*100,
            y:cy+Math.cos(centerMove)*100
        },
        {x:mouse.x,y:mouse.y}
    );
};

希望这对您有所帮助。抱歉多了一些水果,但我必须对其进行测试,所以尽管我只是将其全部复制为答案。

我为那些想看到它运行的人添加了一个 fiddle 。 PointA be 会自动移动(所以当您移动鼠标时看起来有点奇怪)因为我懒得添加适当的界面。

更新: 我已经更新了答案和 fiddle ,试图为更新后的问题找到更好的解决方案。不幸的是,我无法满足新的要求,尽管根据我的分析,我发现这些要求提出了一个无法解决的问题。即当螺旋 Angular 接近零时,比例(在解中)接近无穷大,渐近线在 PI/4 附近,但因为这只是一个近似值,所以一切都变得毫无意义。 A 点和 B 点有一组位置无法拟合螺旋线。这是我的解释,并不意味着没有解决方案,因为我没有提供证据。

Fiddle (updated)

关于javascript - HTML5 Canvas 斐波那契螺旋线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33232159/

相关文章:

javascript - 在 Protractor 中按值选择选项失败

javascript - Angularjs 深度 $watch 不工作

javascript - jQuery/Href 参数

javascript - 同步数据会减慢应用程序

html - 背景附件: fixed not working on android/ios

javascript - 有没有办法使用分配的值从对象中提取特定的键名称?

javascript - 如何在主干 View 中使用 "this"?

javascript - Bootstrap 多选 : Adding images instead of text

javascript - 如何根据行中另一个单元格的内容修改 HTML 表格行的内容?

javascript - 使用 JQuery.throwable 将 div 添加到场景