Javascript 使用看起来被拉伸的 <canvas> 元素绘制的网格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4172246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:14:17  来源:igfitidea点击:

Grid drawn using a <canvas> element looking stretched

javascriptjqueryhtmlcanvasgrid

提问by Acorn

I'm trying to draw a grid on a <canvas>element with the ultimate goal of making a Go board.

我正在尝试在<canvas>元素上绘制网格,最终目标是制作Go board

For some reason the grid is looking stretched, with the lines being thicker than 1 pixel and the spacing being completely wrong. It doesn't even start in the (10,10)position..

出于某种原因,网格看起来被拉伸了,线条比 1 像素粗,间距完全错误。它甚至没有从这个(10,10)位置开始..

It would be great if someone could take a look at tell me what I'm doing wrong.

如果有人可以看看告诉我我做错了什么,那就太好了。

http://jsfiddle.net/h2yJn/

http://jsfiddle.net/h2yJn/

alt text

替代文字

回答by Acorn

I've found the problem. I was setting the dimensions of the <canvas>using CSS, when you actually have to set the width and height attributes. This was causing it to be stretched/skewed.

我找到了问题所在。<canvas>当您实际上必须设置宽度和高度属性时,我正在设置使用 CSS的尺寸。这导致它被拉伸/歪斜。

var canvas = $('<canvas/>').attr({width: cw, height: ch}).appendTo('body');

http://jsfiddle.net/h2yJn/66/

http://jsfiddle.net/h2yJn/66/

alt text

替代文字

回答by pts

Please try it outside jsfiddle, maybe jsfiddle is applying some linear transformation.

请在 jsfiddle 之外尝试一下,也许 jsfiddle 正在应用一些线性变换。

Also please make sure that you add 0.5 everywhere to both x and y coordinates. Alternatively, you can apply translate(0.5, 0.5) to shift all coordinates by half a pixel.

另外,请确保在 x 和 y 坐标中随处添加 0.5。或者,您可以应用 translate(0.5, 0.5) 将所有坐标移动半个像素。