i have started canvas. move elements on mousemove in canvas. wasn't problem added resize function make fluid. after width , height of canvas set after resizing when set width , height(so have resize window width , height canvas or has no width , height) , "eyes" leaving track after themself canvas not clearing or updating(?) cannot find out why. appreciated.
demo : https://jsfiddle.net/62jkx9rj/2/
js :
window.requestanimframe = (function() { return window.requestanimationframe || window.webkitrequestanimationframe || window.mozrequestanimationframe || window.orequestanimationframe || window.msrequestanimationframe || function(callback) { window.settimeout(callback, 1000 / 60); }; })(); var ctx, widthcanvas, heightcanvas, lefteye, righteye, mouse; eye = function(pos) { this.pos = { x: pos.x, y: pos.y }; this.center = { x: pos.x, y: pos.y }; this.translation = { x: (window.innerwidth / 2 - canvas.width / 2) + this.center.x, y: this.center.y }; } eye.prototype.draw = function() { ctx.beginpath(); ctx.arc(this.pos.x, this.pos.y, 7, 0, math.pi * 2); ctx.fillstyle = '#333'; ctx.fill(); ctx.beginpath(); ctx.arc(this.pos.x, this.pos.y - 4, 3, 0, math.pi * 2); ctx.fillstyle = '#fff'; ctx.fill(); } eye.prototype.update = function() { var deltax = mouse.x - this.translation.x; var deltay = mouse.y - this.translation.y; var mag = math.sqrt(deltax * deltax + deltay * deltay); var anglerad = math.atan2(deltay, deltax); var newposx = this.center.x + 6 * math.cos(anglerad); var newposy = this.center.y + 6 * math.sin(anglerad); this.pos.x += (newposx - this.pos.x) / 5; this.pos.y += (newposy - this.pos.y) / 5; } var init = function() { var canvas = document.getelementbyid("canvas"); var $canvas = $('#canvas'); ctx = canvas.getcontext('2d'); container = $("body"); widthcanvas = 300; heightcanvas = 250; $(window).resize(resizecanvas); function resizecanvas() { widthcanvas = $canvas.attr('width', $(container).width()); heightcanvas = $canvas.attr('height', $(container).height()); } resizecanvas(); canvas.width = widthcanvas; canvas.height = heightcanvas; lefteye = new eye({ x: 130, y: 95 }); righteye = new eye({ x: 160, y: 85 }); mouse = { x: 0, y: 0 }; bindeventhandlers(); draw(); } var draw = function() { ctx.clearrect(0, 0, widthcanvas, heightcanvas); lefteye.update(); righteye.update(); lefteye.draw(); righteye.draw(); requestanimframe(draw); } var bindeventhandlers = function() { document.onmousemove = function(e) { mouse.x = e.pagex; mouse.y = e.pagey; } } init();
here's working version: https://jsfiddle.net/62jkx9rj/6/
i have 1st problem fixed: have both $canvas, canvas. removed $canvas:
function resizecanvas() { widthcanvas = canvas.width = $(container).width(); heightcanvas = canvas.height = $(container).height(); }
and here's fix 2nd problem. because of confusion of $canvas, canvas. change 1st line of draw:
var draw = function() { ctx.clearrect(0, 0, canvas.width, canvas.height);
Comments
Post a Comment