HTML Canvas 渐变动画
在下面的示例中,如何执行以下操作
当我在 createGradient 函数中创建渐变时,只有第一个圆弧具有多种颜色,第二个圆弧具有单一颜色
当调用 animate 函数时,我只想更改指定的渐变而不是全部
function init() {
can = document.getElementById("can");
ctx = can.getContext("2d");
drawGradients();
var t=setTimeout("animate()",3000);
}
function drawGradients() {
var points = [[50,50,5, 50,50,50], [275,275,5, 275,275,50]];
for ( var i=0; i < points.length; i ++ ) {
var cords = points[i];
createGradient ( points[i] );
}
}
function createGradient( cds) {
var grad = ctx.createRadialGradient( cds[0],cds[1],cds[2],cds[3],cds[4],cds[5]);
grad.addColorStop(0, 'white');
grad.addColorStop(1, 'black');
ctx.fillStyle=grad;
ctx.arc(cds[3],cds[4], cds[5], 0, 2 * Math.PI);
ctx.fill();
}
function animate() {
var cds =[50,50,5, 50,50,50];
var grad = ctx.createRadialGradient( cds[0],cds[1],cds[2],cds[3],cds[4],cds[5]);
grad.addColorStop(0, 'white');
grad.addColorStop(1, 'blue');
ctx.fillStyle=grad;
ctx.arc(cds[3],cds[4], cds[5], 0, 2 * Math.PI);
ctx.fill();
}
</script>
In the following example , How do I do the following
When I create the gradients in createGradient function, Only the first arc has multiple color, the second arc has a single color
When the animate function is called , I would like to change only a specified gradient and not all of them
function init() {
can = document.getElementById("can");
ctx = can.getContext("2d");
drawGradients();
var t=setTimeout("animate()",3000);
}
function drawGradients() {
var points = [[50,50,5, 50,50,50], [275,275,5, 275,275,50]];
for ( var i=0; i < points.length; i ++ ) {
var cords = points[i];
createGradient ( points[i] );
}
}
function createGradient( cds) {
var grad = ctx.createRadialGradient( cds[0],cds[1],cds[2],cds[3],cds[4],cds[5]);
grad.addColorStop(0, 'white');
grad.addColorStop(1, 'black');
ctx.fillStyle=grad;
ctx.arc(cds[3],cds[4], cds[5], 0, 2 * Math.PI);
ctx.fill();
}
function animate() {
var cds =[50,50,5, 50,50,50];
var grad = ctx.createRadialGradient( cds[0],cds[1],cds[2],cds[3],cds[4],cds[5]);
grad.addColorStop(0, 'white');
grad.addColorStop(1, 'blue');
ctx.fillStyle=grad;
ctx.arc(cds[3],cds[4], cds[5], 0, 2 * Math.PI);
ctx.fill();
}
</script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的第一个问题是因为它在第二遍上重绘两个弧。这是因为你从未关闭道路。由于它们位于同一路径上,因此它们仅获得一个渐变,因此看起来一个形状没有获得渐变,但实际上它正在使用另一形状的颜色!
要解决此问题,请执行以下操作:
这也将解决您的动画问题,现在动画只会更改其中一个渐变。
工作代码:
http://jsfiddle.net/8AB3D/
Your first problem is because it is redrawing both arcs on the second pass. This is because you never closed the path. Since they are on the same path, they only get one gradient, so it looks like one shape didn't get a gradient, but really it is using the color from the other shape!
To fix do:
This will also fix your animate problem, and now animate will only change one of the gradients.
Working code:
http://jsfiddle.net/8AB3D/