Canvas 鼠标/手指按下和松开事件

如果只有 Web 端,那么按下和松开就只有 onmousedown 和 omouseup 事件

如果加上移动端,就需要再添加 ontouchstart 和 otouchend 事件了

移动端的我们先不讲,因为我想等到 微信小游戏 教程里再来说明

本章节我们来讲讲 onmousedown 和 omouseup 事件

事件 描述
onmousedown 当按下鼠标按钮时运行脚本
onmouseup 当松开鼠标按钮时运行脚本

这两个事件有什么用呢?

在游戏开发里面,它们的用处可大呢,因为意味着开始发射子弹打怪了 (脑补下微信的打飞机游戏)

事件本身没什么好说,我们直接写一个范例吧

我们这个范例,但按下鼠标时每隔 200ms 生成一个小球,松开鼠标时就停止生成小球

这个小球有一个初始的速度,它会自己运动 10 秒的时间

<!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;
var balls = [];

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;
          }
    }
};

function draw() {
    ctx.clearRect(0,0,c.width,c.height);
    ctx.strokeRect(0,0,c.width,c.height);
    var cur = Date.now();
    for( var i = 0; i < balls.length;i++)
    {
        if ( cur - 10000 >= balls[i].created_at )
        {
            balls.shift();
            continue;
        }
        balls[i].pos_that();
        balls[i].draw(ctx);
    }
    rq = window.requestAnimationFrame(draw);
}

function createBall(x,y) {
    var b = new Ball();
    b.x = x;
    b.y = y;
    b.created_at = Date.now();
    balls.push(b);
}


c.addEventListener('mousedown', function(e){
  tt = setInterval(function(){createBall(e.offsetX,e.offsetY);},200);
});

c.addEventListener('mouseup', function(e){
  clearInterval(tt)
});

rq = window.requestAnimationFrame(draw)

</script>

Canvas 基础教程

关于   |   FAQ   |   我们的愿景   |   广告投放   |  博客

♥   简单教程,简单编程 - IT 入门首选站

Copyright © 2013-2022 简单教程 twle.cn All Rights Reserved.