如何用动画填充画布形状?
Posted
技术标签:
【中文标题】如何用动画填充画布形状?【英文标题】:How can I fill canvas shape with animation? 【发布时间】:2014-06-21 01:41:00 【问题描述】:我是画布新手。我有一个画布形状,想将其填充为动画。
HTML
<canvas id="canvas" ></canvas>
JS
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d");
context.beginPath();
context.moveTo(109,15);
context.bezierCurveTo(121,36,133,57,144,78);
context.bezierCurveTo(160,109,176,141,188,175);
context.bezierCurveTo(206,226,174,272,133,284);
context.bezierCurveTo(79,300,24,259,25,202);
context.bezierCurveTo(25,188,30,174,35,161);
context.bezierCurveTo(53,115,76,73,100,31);
context.bezierCurveTo(103,26,106,21,109,15);
context.lineWidth = 10;
context.strokeStyle="#0092f9";
context.stroke();
context.fillStyle="rgb(43,146,255)";
context.beginPath();
context.moveTo(181,229);
context.bezierCurveTo(179,232,178,235,176,238);
context.bezierCurveTo(171,247,165,254,158,260);
context.bezierCurveTo(150,266,141,269,132,272);
context.bezierCurveTo(126,274,119,275,112,275);
context.bezierCurveTo(108,276,104,275,100,275);
context.bezierCurveTo(92,274,84,272,76,269);
context.bezierCurveTo(67,265,60,259,53,251);
context.bezierCurveTo(48,245,43,238,39,231);
context.bezierCurveTo(39,230,38,230,39,229);
context.bezierCurveTo(39,228,40,229,40,229);
context.bezierCurveTo(52,230,63,231,75,230);
context.bezierCurveTo(79,229,84,228,89,228);
context.bezierCurveTo(97,227,104,227,112,229);
context.bezierCurveTo(116,230,120,230,124,230);
context.bezierCurveTo(130,231,137,231,143,231);
context.bezierCurveTo(148,231,153,230,158,230);
context.bezierCurveTo(165,229,173,228,181,229);
context.fill();
将形状起点作为;
和形状端点为;
我想用动画填充它,像 jquery animate 函数一样缓慢增加液体。我该怎么做?
Code example
【问题讨论】:
您需要以编程方式进行。 (数学)developer.mozilla.org/en-US/docs/Web/API/… 【参考方案1】:您可以使用 context.clip 将您的液体限制为仅在容器中绘制。
这是示例代码和演示:http://jsfiddle.net/m1erickson/jM4hW/
// draw the container
ctx.beginPath();
ctx.moveTo(109,15);
ctx.bezierCurveTo(121,36,133,57,144,78);
ctx.bezierCurveTo(160,109,176,141,188,175);
ctx.bezierCurveTo(206,226,174,272,133,284);
ctx.bezierCurveTo(79,300,24,259,25,202);
ctx.bezierCurveTo(25,188,30,174,35,161);
ctx.bezierCurveTo(53,115,76,73,100,31);
ctx.bezierCurveTo(103,26,106,21,109,15);
ctx.lineWidth=linewidth;
ctx.strokeStyle=strokestyle;
ctx.stroke();
// make the container a clipping region
// all subsequent drawings will only appear inside the container
ctx.clip();
// now draw the liquid
// the liquid will be drawn only where
// it is inside the clipping region (the container)
ctx.fillRect(0,150,canvas.width,500);
【讨论】:
以上是关于如何用动画填充画布形状?的主要内容,如果未能解决你的问题,请参考以下文章