本文介绍了如何使用鼠标事件代替HTML5 canvas和jquery的keycode?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将以下事件管理从键码替换为鼠标。
I'd to like to replace the following event management from keycode to mouse. How do I go about doing it?
现在支持的浏览器= FF 3.6x。
Supported browser for now = FF 3.6x.
// this block of code needs to be replaced
$(document).keydown(function(e) {
//console.log(e.keyCode);
switch(e.keyCode) {
case 38: // down
draw(x,y--);
break;
case 40: // up
draw(x,y++);
break;
case 37: // left
draw(x--,y);
break;
case 39: // right
draw(x++,y);
break;
default:
draw(x,y);
}
});
// to be replaced with something like the following and add control
// we need to get the x,y coordinates upon mouse click, not onload, how?
$(document).onmousemove = mouseMove;
function mouseMove(ev){
ev = ev || window.event;
var mousePos = mouseCoords(ev);
alert( mousePos);
}
function mouseCoords(ev){
if(ev.pageX || ev.pageY){
return {x:ev.pageX, y:ev.pageY};
return {x:ev.pageX};
}
return {
x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
y:ev.clientY + document.body.scrollTop - document.body.clientTop
};
}
// keep
function draw(x,y) {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var canvas = $("#canvas")[0];
var ctx = canvas.getContext("2d");
ctx.font = "15pt Verdana";
// var ctx.lineWidth = 1;
ctx.clearRect(0,0,500,500);
x1 = x + 50;
y1 = y + 50;
ctx.fillText("Oh my god his pant is falling down",x1,y1);
x2 = x + 100;
y2 = y + 100;
ctx.fillText("shi shi we did not see anything",x2,y2);
x3 = x + 200;
y3 = y + 200;
ctx.fillText("what a happy man!",x3,y3);
}
draw(x,y);
推荐答案
基本上,您将一个onmousemove事件处理程序添加到画布上,并且需要处理(X,Y)代码,这在不同浏览器中显然是不同的属性。 layerX& layerY for FireFox; offsetX& offsetY for Opera。
Basically, you add an onmousemove event handler to the canvas, and that needs to handle your code for (X,Y) which is apparently a different attribute in different browsers. layerX & layerY for FireFox; offsetX & offsetY for Opera.
这篇关于如何使用鼠标事件代替HTML5 canvas和jquery的keycode?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!