Canvas How to - Reference canvas from context








Question

We would like to know how to reference canvas from context.

Answer


<!--from   ww  w  .java  2s .  co  m-->



<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
function lineDraw() {   
    var canvas=document.getElementById("myCanvas");
    var context=canvas.getContext("2d");
    context.canvas.width = context.canvas.width;
    context.moveTo(0,0);
    context.lineTo(event.clientX,event.clientY);
    context.stroke();
}
//]]>  
</script>
</head>
<body onmousemove="lineDraw()">
   <canvas id="myCanvas" width="640" height="480"/>
</body>
</html>

The code above is rendered as follows: