JavaScript
语言:
JaveScriptBabelCoffeeScript
确定
/* compact way of setting PI = Math.PI, sin = Math.sin & so on... :D */
Object.getOwnPropertyNames(Math).map(function(p) {
window[p] = Math[p];
});
var c = document.querySelector('.c') /* canvas element */ ,
w /* canvas width */ , h /* canvas height */ ,
ctx = c.getContext('2d') /* get canvas context */ ,
/* start, end & control points for our quadratic Bézier curve */
start, end, control;
/* FUNCTIONS */
var initCanvas = function() {
/* canvas element stles that were set via CSS */
var s = getComputedStyle(c);
/*
* get canvas dimensions as they were set via CSS
* use them to set w & h variables and
* canvas width & height attributes
* (don't forget about these,
* canvas looks stretched if you do)
*/
w = c.width = ~~s.width.split('px')[0];
h = c.height = ~~s.height.split('px')[0];
/*
* pick initial start, end and control points
* for our quadratic Bézier curve
*/
start = {
'x': round(w / 4),
'y': round(h / 2)
};
end = {
'x': round(3 * w / 4),
'y': round(h / 2)
};
control = {
'x': round(w / 2),
'y': round(h / 2)
};
/*
* make sure the entire canvas is cleared
* before anything else
* this has no visual effect when init is called
* for the first time
*/
ctx.clearRect(0, 0, w, h);
/* set stroke and fill styles */
ctx.strokeStyle = '#fff';
/* note that the fill is semitransparent, alpha = .2 */
ctx.fillStyle = 'hsla(200, 25%, 7%, .2)';
/* call function that handles drawing stuff */
drawOnCanvas();
};
var drawOnCanvas = function() {
/*
* don't clear canvas before drawing omething new
* just cover it with a semitransparent rectangle
* this leaves what was drawn by previous calls
* visible, but somehow "faded",
* creating the "trace effect"
*/
ctx.rect(0, 0, w, h);
ctx.fill();
/*
* draw our quadratic Bézier curve
* for the current control point
*/
ctx.beginPath();
ctx.moveTo(start.x, start.y);
ctx.quadraticCurveTo(control.x, control.y, end.x, end.y);
ctx.fill(); /* for inside the curve */
ctx.stroke();
};
/* START IT ALL */
/*
* inside the setTimeout so that
* the dimensions do get set via CSS before calling
* the init function
*/
setTimeout(function() {
initCanvas();
c.addEventListener('mousemove', function(e) {
/*
* coordinates of the control point
* of a quadratic Bézier curve whose midpoint
* is at the current mouse position
*/
control = {
'x': round(2 * e.clientX - (start.x + end.x) / 2),
'y': round(2 * e.clientY - (start.y + end.y) / 2)
};
/* draw this quadratic Bézier curve */
drawOnCanvas();
}, false);
/* fix looks on resize so it doesn't look stretched */
addEventListener('resize', initCanvas, false);
}, 15);