Friday, 15 June 2012

Unable to convert Javascript code to JQuery -



Unable to convert Javascript code to JQuery -

like of beginners, have been trying larn jquery transforming javascript code jquery. here part of code utilize html canvas , allows user draw , delete content in canvas using jquery:

function init() { canvas = $('#can'); ctx = canvas.getcontext("2d"); w = canvas.width; h = canvas.height; canvas.addeventlistener("mousemove", function (e) { findxy('move', e) }, false); canvas.addeventlistener("mousedown", function (e) { findxy('down', e) }, false); canvas.addeventlistener("mouseup", function (e) { findxy('up', e) }, false); canvas.addeventlistener("mouseout", function (e) { findxy('out', e) }, false);}

this code in javascript, have changed selectors utilize jquery. getting error in 3rd line of code as: uncaught typeerror: undefined not function

could please guide why getting this. thanks

getcontext not jquery property, hence need access underlying dom element , phone call on that:

ctx = canvas[0].getcontext("2d");

also, jquery convention utilize $ prefix on variable containing jquery object. width , height methods, should have trailing brackets. finally, if want utilize jquery, utilize attach events too:

function init() { var $canvas = $('#can'); var ctx = $canvas[0].getcontext("2d"); var w = $canvas.width(); var h = $canvas.height(); $canvas .on("mousemove", function(e) { findxy('move', e); }) .on("mousedown", function(e) { findxy('down', e); }) .on("mouseup", function(e) { findxy('up', e); }) .on("mouseout", function(e) { findxy('out', e); }); }

javascript jquery html html5-canvas

No comments:

Post a Comment