Canvas 跟随鼠标/手指
临时突然间想到还有鼠标移动和手指移动事件 omousemove
和 ontouchmove
前者一般时 PC 端,后者一般是移动设备
同样的,本章节我们只讨论 omousemove
事件 | 描述 |
---|---|
onmouseover | 当鼠标指针移至元素之上时运行脚本 |
这个事件有什么用呢?
我们一般用它来做鼠标跟随效果,比如移动鼠标时,把本方的飞机也移动下(脑补下微信的打飞机游戏)
事件本身没什么好说,我们直接写一个范例吧
很简单,就是当鼠标按下时设置鼠标一个标记,鼠标松开时取消标记
在鼠标按下状态,当鼠标移动时,小球也会移动
对了,小球的圆心就是鼠标的坐标
<!DOCTYPE html> <meta charset="utf-8"> <canvas id="canvas-1" width="400" height="200"> </canvas> <script> var c = document.getElementById('canvas-1'); var ctx = c.getContext('2d'); var rq; var tt; is_mousedown = false; function Ball() { this.x = 10; this.y = 10; this.vx = 5; this.vy = 2; this.created_at = 0; this.radius = 10, this.color = 'blue', this.draw = function(ctx) { ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true); ctx.closePath(); ctx.fillStyle = this.color; ctx.fill(); } this.pos_that = function() { this.x += this.vx; this.y += this.vy; this.vy *= .99; this.vy += .25; if (this.y + this.vy > c.height || this.y + this.vy < 0) { this.vy = -this.vy; } if (this.x + this.vx > c.width || this.x + this.vx < 0) { this.vx = -this.vx; } } }; var ball = new Ball(); ctx.strokeRect(0,0,c.width,c.height); ball.draw(ctx); c.addEventListener('mousemove', function(e){ if ( is_mousedown ) { ctx.clearRect(0,0,c.width,c.height); ctx.strokeRect(0,0,c.width,c.height); ball.x = e.offsetX ; ball.y = e.offsetY; ball.draw(ctx); } }); c.addEventListener('mousedown', function(e){ is_mousedown = true; }); c.addEventListener('mouseup', function(e){ is_mousedown = false; }); rq = window.requestAnimationFrame(draw) </script>