简体   繁体   English

HTML5 Canvas:在负载下绘制的贝塞尔曲线

[英]HTML5 Canvas: Bezier curve to draw on load

I have draw the Bezier Curve. 我已经绘制了贝塞尔曲线。 But I Want Animate the Bezier Curve in onload for 1 time. 但我想在加载时对Bezier曲线进行动画处理1次。

Please help me.. 请帮我..

Here the below code: 这里下面的代码:

  window.onload = function() { var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var x=10, y=25; function curve() { context.beginPath(); context.moveTo(214, 0); context.bezierCurveTo(328, 80, 153, 82, 216, 162); context.lineWidth = 10; context.strokeStyle = 'gray'; context.stroke(); } curve(); }; 
 <body> <canvas id="canvas" width="300" height="300" style="text-align: left; border: 1px solid black; position: absolute; left: 100px;"></canvas> </body> 

Curve draw on 0 to (328, 80, 153, 82, 216, 162) 在0至(328,80,153,82,216,162)上绘制曲线

If you want to animate the curve, you can structurate your code like that : 如果要对曲线进行动画处理,可以像这样来构造代码:

var snake = {
    points:[ {x:100,y:100},{x:100,y:150},{x:100,y:200},{x:100,y:250} ]
}

function loop(){
    physic( snake )
    display( snake )
}
setInterval( loop, 20 )

In the physic function, you update points in the snake structure according to what you want. 在物理功能中,您可以根据需要更新蛇形结构中的点。 In the display function you do something like that : 在显示功能中,您可以执行以下操作:

function display( snake ){

    var point = snake.points[0];

    ctx.beginPath();
    ctx.lineWidth = 10;
    ctx.moveTo( point.x, point.y );

    for( i=0; i< snake.points.length-1; i++ ){

        point = snake.points[i];

        var xc = (point.x + snake.points[i + 1].x) / 2;
        var yc = (point.y + snake.points[i + 1].y) / 2;

        ctx.quadraticCurveTo( point.x, point.y, xc, yc );
    }

    ctx.stroke();
}

The difficult part is the physic function. 困难的部分是物理功能。

function physic( snake ){

    snake.points[2].x++ // An example
}

You can cheat to get the effect, although the animation does not bend according to the line (you have to stop the timer and this might not work if there are other drawn object near it) 您可以作弊以获得效果,尽管动画不会按照线条弯曲(您必须停止计时器,并且如果附近有其他绘制的对象,这可能不起作用)

http://jsfiddle.net/o9k83k0g/ http://jsfiddle.net/o9k83k0g/

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var x=10, y=25;
var show=0;    

function curve() {
  context.beginPath();
  context.moveTo(214, 0);
  context.bezierCurveTo(328, 80, 153, 82, 216, 162);
  context.lineWidth = 10;
  context.strokeStyle = 'gray';
  context.stroke();

  context.beginPath();   
  context.fillStyle = 'white';
  context.fillRect(160,0+show,100,175-show);
  context.stroke();
  show=show+1;
 }
setInterval(function(){curve();}, 30);

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

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