javascript - HTML5 - Canvas Element & Custom Cursor -
html5 document - canvas element not running javascript parameters customized 'rectangle' cursor. please :)
<head> <title>canvas element & custom cursor</title> </head> <body id="body" style="background-color:red;"> <canvas id="canvas" width="600" height="400" style="background- color:white;"> </canvas> <script> funtion canvasproperties(){ var canvas = document.getelementbyid("canvas"); canvas = canvas.getcontext("2d"); window.addeventlistener("mousemove", customcursor, false);} function customcursor(){ canvas.clearrect(0,0,600,400); var xposition = clientx; var yposition = clienty; canvas.fillrect(xposition, yposition, 100, 100);} window.addeventlistener("load", canvasproperties, false); </script> </body> </html>
there several issues here, pointed out in scimonster's answer, important 1 remains.
for rectangle placed correctly need "correct" mouse positions. mouse positions relative client window while need them relative canvas element.
also, overriding canvas context. use separate variable it, , place in global (parent) scope.
here full version (inside script tags):
var canvas, context; // place in global scope function canvasproperties(){ canvas = document.getelementbyid("canvas"); context = canvas.getcontext("2d"); // separate var context... window.addeventlistener("mousemove", customcursor, false); } function customcursor(e){ var canvasrect = canvas.getboundingclientrect(); // position of canvas element var xposition = e.clientx - canvasrect.left; // adjust mouse positions var yposition = e.clienty - canvasrect.top; // become relative canvas context.clearrect(0,0,600,400); // use context context.fillrect(xposition - 50, yposition - 50, 100, 100); } window.addeventlistener("load", canvasproperties, false);
<canvas id="canvas" width=600 height=400></canvas>
Comments
Post a Comment