鼠标事件未定义

时间:2012-04-22 21:51:49

标签: javascript html javascript-events html5-canvas

我在网页上有一个HTML5画布,其中有一个JavaScript函数可以在画布上绘制图像。我正在尝试向图像添加一个鼠标事件,以便在单击它时,调用另一个JavaScript函数,它将更新画布上显示的内容。

在Firefox中查看页面时,单击画布上显示的图像时没有任何反应。我正在使用Firebug尝试看看有什么问题,它给了我以下信息:

 mouse_event is not defined
 drawStartButton()index.html (line 107)
 startGame()index.html (line 64)
 (?)()index.html (line 1)
 event = load
 [Break On This Error]  

 ...useX = (mouse_event.clientX-boundingBox.left) * (myGameCanvas.width/boundingBox....

 index.html (line 107)

我用来绘制画布上的开始按钮的功能,以及我添加的鼠标事件如下:

function drawStartButton(){
            image.onload = function(){
                context.drawImage(image, 260.5, 60);
            };
            image.src = "StartButton.png";
            /** Now I need to add an event listener to the area of the canvas on 
                on which the button image is displayed, in order to 'listen' for 
                a click on the button */
            var boundingBox = myGameCanvas.getBoundingClientRect();
            var mouseX = (mouse_event.clientX-boundingBox.left) * (myGameCanvas.width/boundingBox.width);
            var mouseY = (mouse_event.clientY-boundingBox.top) * (myGameCanvas.height/boundingBox.height);
            var pixels = context.getImageData(mouseX, mouseY, 1, 1); }

基本上,我想要做的就是当用户点击按钮时,将调用下面的函数,并将更新画布的内容:

function drawLevelOneElements(){
            var context = canvas.getContext("2d");

            /* Draw the images for numbers 1-10.*/
            var image1 = new Image();
            /* Test that this code is being executed */
            context.moveTo(300, 300);
            context.font = "11pt Calibri";
            context.strokeStyle = "black";
            context.strokeText("Testing",300, 300);
            /* End of test */

            image1.onLoad = function(){
                context.drawImage(image1, 50, 50);
                };
            image1.src="1.png";
        }

感谢您的帮助。 :)

*的 更新 **

似乎我能够通过将变量mouseX,mouseY和pixels放在函数中并将boundingBox.onmousemove属性设置为等于此函数来解决此问题:

boundingBox.onmousemove = function(e){
                var mouseX = e.pageX - this.offsetLeft;
                var mouseY = e.pageY - this.offsetTop;
                var pixels = context.getImageData(mouseX, mouseY, 1, 1);
            }

1 个答案:

答案 0 :(得分:0)

通过将变量mouseX,mouseY和pixel放入函数中并将boundingBox.onmousemove属性设置为与此函数相同,看来我能够解决此问题:

boundingBox.onmousemove = function(e){
                var mouseX = e.pageX - this.offsetLeft;
                var mouseY = e.pageY - this.offsetTop;
                var pixels = context.getImageData(mouseX, mouseY, 1, 1);
            }