我画了Bezier曲线。但我希望在onload中为Bezier曲线设置Animate一次。
请帮帮我..
以下代码:
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>
曲线绘制0到(328,80,153,82,216,162)
答案 0 :(得分:0)
如果要为曲线设置动画,可以按照以下方式构建代码:
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 )
在物理功能中,您可以根据需要更新蛇形结构中的点。 在显示功能中,您可以执行以下操作:
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();
}
困难的部分是物理功能。
function physic( snake ){
snake.points[2].x++ // An example
}
答案 1 :(得分:0)
虽然动画不会根据线条弯曲,但您可以作弊来获得效果 (你必须停止计时器,如果附近有其他绘制的物体,这可能不起作用)
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);