使用鼠标坐标绘制画布问题? [英] Canvas drawing using mouse coords issue?

查看:60
本文介绍了使用鼠标坐标绘制画布问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用鼠标的x/y坐标绘制到画布上,但是我绘制的线条总是会画一点,请尝试在此处进行绘制:

I'm drawing to the canvas using the x/y coords of the mouse, but the line that I'm drawing always draws off a little bit, try drawing on here: http://zachrip.net/widgets/onlineedit/index.html (top left) for an example of what I mean. There is no offset so I do not account for it, so I don't know what the issue is?

推荐答案

此处的问题是您正在通过CSS设置画布元素大小,但没有设置绘图表面尺寸.

The problem here is that you are setting the Canvas Element Size through your CSS, but you do not set the Drawing Surface Size.

绘图表面"的默认大小为300px x 150px.由于您没有设置元素大小,而是设置了元素大小,因此浏览器会缩放工程图的表面大小以适合元素.通过鼠标事件获得的x和y坐标对应于元素大小",而不是实际的图纸表面大小".这就是为什么获得偏移量的原因.

The default size of the Drawing Surface is 300px by 150px. Since you do not set it, but set the Element Size, the browser scales the drawing surface size to fit the element. The x and y co-ordinates you get through the mouse event correspond to the Element Size, and not the actual Drawing Surface Size. Which is why you get the offset.

现在,我刚才发布的 小提琴 绘图表面的大小,而不是元素的大小.可以,但是如果您希望使用不同的元素"和绘图表面"尺寸,那么您也可以这样做

Now, the fiddle that I posted earlier merely had you set the size of Drawing Surface, instead of the Element. And that works, but if you'd rather have different Element and Drawing Surface sizes, then you can also do

function scaleCoords(x, y) {
    x = x * DrawingSurfaceSize.width/ElementSize.width;
    y = y * DrawingSurfaceSize.height/ElementSize.height;

    return {x: x, y: y};
}

第二种方法的示例 .

Example for second method.

这篇关于使用鼠标坐标绘制画布问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆