在画布中获取鼠标位置

时间:2013-04-06 23:12:37

标签: javascript html5 canvas mouseevent mouseover

我正在尝试修改this effect以在我的画布中工作。但是,我似乎无法让鼠标位置正常工作。悬停区域不包含在我的画布中。

这是我尝试实现它的CSSdeck:http://cssdeck.com/labs/ukktjtis

效果:

function hoverText(){
window.requestAnimFrame = (function(){
    return  window.requestAnimationFrame       || 
        window.webkitRequestAnimationFrame || 
        window.mozRequestAnimationFrame    || 
        window.oRequestAnimationFrame      || 
        window.msRequestAnimationFrame     || 
        function( callback ){
            window.setTimeout(callback, 1000 / 60);
        };
})();

var canvas = document.getElementById("canvas"),
        ctx = canvas.getContext("2d"),
        keyword = "MacroPlay Games",
        imageData,
        density = 3,
        mouse = {},
        hovered = false,
        colors = ["0,120,232", "8,200,255", "30,140,255"],
        minDist = 20,
        bounceFactor = 0.7;

var W = window.innerWidth, H = window.innerHeight;

canvas.width = W;
canvas.height = H;

document.addEventListener("mousemove", function(e) {
    mouse.x = e.pageX-50;
    mouse.y = e.pageY+200;
}, false);

// Particle Object
var Particle = function() {
    this.w = Math.random() * 10.5;
    this.h = Math.random() * 10.5;
    this.x = -W;
    this.y = -H;
    this.free = false;

    this.vy = -5 + parseInt(Math.random() * 10) / 2;
    this.vx = -4 + parseInt(Math.random() * 8);

    // Color
    this.a = Math.random();
    this.color = colors[parseInt(Math.random()*colors.length)];

    this.setPosition = function(x, y) {
        this.x = x;
        this.y = y;
    };

    this.draw = function() {
        ctx.fillStyle = "rgba("+this.color+","+this.a+")";
        ctx.fillRect(this.x, this.y,  this.w,  this.h);
    }
};

var particles = [];

// Draw the text
function drawText() {
    ctx.clearRect(0, 0, W, H);
    ctx.fillStyle = "#000000";
    ctx.font = "100px 'Arial', sans-serif";
    ctx.textAlign = "center";
    ctx.fillText(keyword, W/2, H/2);
}

// Clear the canvas
function clear() {
    ctx.clearRect(0, 0, W, H);
}

// Get pixel positions
function positionParticles() {
    // Get the data
    imageData = ctx.getImageData(0, 0, W, W);
    data = imageData.data;

    // Iterate each row and column
    for (var i = 0; i < imageData.height; i += density) {
        for (var j = 0; j < imageData.width; j += density) {

            // Get the color of the pixel
            var color = data[((j * ( imageData.width * 4)) + (i * 4)) - 1];

            // If the color is black, draw pixels
            if (color == 255) {
                particles.push(new Particle());
                particles[particles.length - 1].setPosition(i, j);
            }
        }
    }
}

drawText();
positionParticles();


// Update
function update() {
    clear();

    for(i = 0; i < particles.length; i++) {
        var p = particles[i];

        if(mouse.x > p.x && mouse.x < p.x + p.w && mouse.y > p.y && mouse.y < p.y + p.h) 
            hovered = true;

        if(hovered == true) {

            var dist = Math.sqrt((p.x - mouse.x)*(p.x - mouse.x) + (p.y - mouse.y)*(p.y - mouse.y));

            if(dist <= minDist)
                p.free = true;

            if(p.free == true) {
                p.y += p.vy;
                p.vy += 0.15;
                p.x += p.vx;

                // Collision Detection
                if(p.y + p.h > H) {
                    p.y = H - p.h;
                    p.vy *= -bounceFactor;

                    // Friction applied when on the floor
                    if(p.vx > 0)
                        p.vx -= 0.1;
                    else 
                        p.vx += 0.1;
                }

                if(p.x + p.w > W) {
                    p.x = W - p.w;
                    p.vx *= -bounceFactor;
                }

                if(p.x < 0) {
                    p.x = 0;
                    p.vx *= -0.5;
                }
            }
        }

        ctx.globalCompositeOperation = "lighter";
        p.draw();
    }
}


(function animloop(){
    requestAnimFrame(animloop);
    update();
})();    
}

2 个答案:

答案 0 :(得分:1)

高度建议您使用jquery(或某些js lib)来避免跨浏览器问题,例如获取鼠标位置。

您可以使用jquery轻松地在任何浏览器中获取鼠标位置:

// get the position of the canvas relative to the web page
    var canvasOffset=$("#canvas").offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;


// then in the mouse handler, get the exact mouse position like this:
    function handleMouseDown(e){
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);

      // Put your mousedown stuff here

    }


// tell the browser to send mousedown events to the handleMouseDown function
$("#canvas").mousedown(function(e){handleMouseDown(e);});

答案 1 :(得分:1)

我个人更喜欢像hammer.js这样的图书馆。我已经将它用于我的所有项目 - 检查出来,非常好。