简体   繁体   English

鼠标在画布上的运动图像的中心

[英]Mouse on center of moving image on canvas

I am making for school a star catching game. 我正在为学校做一个明星捕捉游戏。 I want the enviroment to change dynamicly so that when i resize browser windows the game will resize with it. 我希望环境能够动态地改变,这样当我调整浏览器窗口大小时,游戏会随之调整大小。

I got the following running code: http://jsfiddle.net/xigolle/yA74f/ 我得到了以下运行代码: http//jsfiddle.net/xigolle/yA74f/

The only problem with that is that the mouse isn't center on the witch. 唯一的问题是鼠标不是女巫的中心。 What is the best way for me to get the mouse on the center on every size? 在每种尺寸上将鼠标放在中心的最佳方法是什么?

The problem lays for sure in this part: 问题在这一部分确定:

 ctx.drawImage(img, this.x, this.y, canvas.width/10, canvas.height/10);

The size of the browser window i get from a event listener who activates when i resize. 我从调整大小时激活的事件监听器获取的浏览器窗口的大小。

And the value is put in canvas.width and canvas.height. 值放在canvas.width和canvas.height中。

I hope you guys can help me :) 我希望你们能帮助我:)

For any more question or unclearance please ask :) 如有任何疑问或不透露请问:)

You have two problems 你有两个问题

The first is your use of drawImage 首先是你使用drawImage

ctx.drawImage(img, this.x, this.y, canvas.width/10, canvas.height/10);

This is going to rescale the witch image in a way that does not keep the proportions, which is why when resizing the window the witch either squishes or expands 这将以不保持比例的方式重新调整女巫形象,这就是为什么在调整窗口大小时女巫要么躲避也要扩大

You should resize the image based on a ratio of the original image size and original canvas size. 您应该根据原始图像大小和原始画布大小的比例调整图像大小。 Then use that ratio times the new canvas size to get the right image size. 然后使用该比率乘以新的画布大小以获得正确的图像大小。

//Original canvas width/height
var initialWidth = 500, initialHeight = 500;
var initialImgWidth = 120, initialImgHeight = 65;
var wRatio =  initialImgWidth/initialWidth, hRatio = initialImgHeight/initialHeight;
...
ctx.drawImage(img, this.x, this.y, canvas.width*wRatio, canvas.height*hRatio);

Now that we have the image resize resolved now we can center the image on the mouse Now to center you have to take the mouse x/y and minus each with 1/2 of width/height of the rescaled witch respectively 现在我们已经解析了图像调整大小现在我们可以将图像居中放在鼠标中心现在要居中,您必须分别使用鼠标x / y和减去每个重新调整的女巫的宽度/高度的1/2

Witch.x = event.pageX-((canvas.width*wRatio)/2);
Witch.y = event.pageY-((canvas.height*hRatio)/2);

JSFiddle 的jsfiddle

EDIT 编辑

My rescale calculations were wrong, for now to scale the image for now just scale it by its original dimensions 我的重新缩放计算是错误的,现在要缩放图像,现在只需按原始尺寸进行缩放

var imgWScale = initialImgWidth/2;
var imgHScale = initialImgHeight/2;
...
ctx.drawImage(img, this.x, this.y, imgWScale,imgHScale);
...
Witch.x = event.pageX-(imgWScale/2);
Witch.y = event.pageY-(imgHScale/2);

Just remember to center just get the images width/height and divide in half and then take that from the mouse coordinates. 只记得中心只是获取图像宽度/高度并分成两半,然后从鼠标坐标中取出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM