HTML5 Canvas贝塞尔曲线动画
点击这里可以查看动画效果: http://www.108js.com/article/article3/zip1/BezierAnim.html 欢迎访问博主的网站:http://www.108js.com
效果图:
代码:
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
var canvas = document.getElementById("myCanvas");
var context = myCanvas.getContext("2d");
var animpts=;
var deltas=;
var gradient;//线性渐变
var w=canvas.width;
var h=canvas.height;
function main() {
context.clearRect(0, 0, w,h);
step(w,h);
render(w, h, context);
requestAnimFrame(function() {
main();
});
}
function init() {
gradient = context.createLinearGradient(0,0,200,200);
gradient.addColorStop(0,'red');
gradient.addColorStop(1,'yellow');
context.fillStyle = gradient;
context.strokeStyle="blue";
context.lineWidth=10;
reset(w,h);
render(w, h, context)
main();
}
function animate(pts, deltas, index, limit) { var newpt = pts + deltas; if (newpt <= 0) { newpt = -newpt; deltas = (Math.random() * 4 + 2); } else if (newpt >= limit) { newpt = 2 * limit - newpt; deltas = - (Math.random() * 4 + 2); } pts = newpt; }
function reset(w,h) {
for (var i = 0; i < 12; i += 2) {
animpts = (Math.random() * w);
animpts = (Math.random() * h);
deltas = (Math.random() * 6.0 + 4.0);
deltas = (Math.random() * 6.0 + 4.0);
if (animpts > w / 2) {
deltas = -deltas;
}
if (animpts > h / 2) {
deltas = -deltas;
}
}
gradient = context.createLinearGradient(0,0,w*0.7,h*0.7);
gradient.addColorStop(0,'red');
gradient.addColorStop(1,'yellow');
}
function step(w, h) {
for (var i = 0; i < 12; i += 2) {
animate(animpts, deltas, i + 0, w);
animate(animpts, deltas, i + 1, h);
}
}
function render(w, h, context) {
var ctrlpts = animpts;
var len = ctrlpts.length;
var prevx = ctrlpts;
var prevy = ctrlpts;
var curx = ctrlpts;
var cury = ctrlpts;
var midx = (curx + prevx) / 2;
var midy = (cury + prevy) / 2;
context.beginPath();
context.moveTo(midx, midy);
for (var i = 2; i <= ctrlpts.length; i += 2) {
var x1 = (midx + curx) / 2;
var y1 = (midy + cury) / 2;
prevx = curx;
prevy = cury;
if (i < ctrlpts.length) {
curx = ctrlpts;
cury = ctrlpts;
} else {
curx = ctrlpts;
cury = ctrlpts;
}
midx = (curx + prevx) / 2;
midy = (cury + prevy) / 2;
var x2 = (prevx + midx) / 2;
var y2 = (prevy + midy) / 2;
context.bezierCurveTo(x1, y1, x2, y2, midx, midy);
}
context.closePath();
context.stroke();
context.fill();
}
window.onload=init;
热情奉献:HTML5 Canvas绘图与动画学习59例源码: http://www.108js.com/example.html