Permalink
Switch branches/tags
Nothing to show
Find file
Fetching contributors…
Cannot retrieve contributors at this time
84 lines (73 sloc) 2.08 KB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Drawing a line from the canvas centre to the mouse position</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<link rel="stylesheet" href="styles.css" type="text/css">
</head>
<body>
<header><h1>Drawing a line from the canvas centre to the mouse position</h1></header>
<canvas></canvas>
<nav><h2>Go to step:</h2> <ol><li><a href="1_simple.html">1</a></li>
<li><a href="2_wiping.html">2</a></li>
<li><a href="3_translation.html">3</a></li>
<li><strong>4</strong></li>
<li><a href="5_opposingline.html">5</a></li>
<li><a href="6_opposingline_factored.html">6</a></li>
<li><a href="7_shadow.html">7</a></li>
<li><a href="8_blur.html">8</a></li>
<li><a href="9_shadow_blur.html">9</a></li>
<li><a href="10_auto.html">10</a></li></ol></nav>
<script>
// grab the canvas element, get the context for API access and
// preset some variables
var canvas = document.querySelector( 'canvas' ),
c = canvas.getContext( '2d' ),
mouseX = 0,
mouseY = 0,
width = 300,
height = 300,
distx = 0,
disty = 0,
hw = width / 2,
hh = height / 2;
// resize the canvas
canvas.width = width;
canvas.height = height;
function draw() {
// calculate the distance caused by the offset
distx = mouseX - hw;
disty = mouseY - hh;
c.clearRect( 0, 0, width, height );
// set the colour
c.save();
c.translate( hw, hh);
c.beginPath()
c.strokeStyle = '#fff';
c.moveTo( 0, 0 );
c.lineTo( distx, disty );
c.closePath();
c.stroke();
c.fillStyle = 'lime';
c.beginPath()
c.arc( distx, disty, 20 , 0, Math.PI*2, true );
c.closePath();
c.fill();
c.restore();
}
// get the mouse position on the canvas (some browser trickery involved)
canvas.addEventListener( 'mousemove', function( event ) {
if( event.offsetX ){
mouseX = event.offsetX;
mouseY = event.offsetY;
} else {
mouseX = event.pageX - event.target.offsetLeft;
mouseY = event.pageY - event.target.offsetTop;
}
// call the draw function
draw();
}, false );
</script>
</body>
</html>