Run*_*hia 2 html javascript grid canvas
我正在尝试创建一个简单的画布网格,它既适合播放器当前的缩放级别,也适合某个画布高度/宽度比例的屏幕限制。这是我到目前为止所得到的:
JS:
var bw = window.innerWidth / 2; //canvas size before padding
var bh = window.innerHeight / 1.3; //canvas size before padding
//padding around grid, h and w
var pW = 30;
var pH = 2;
var lLimit = 0; //9 line limit for both height and width to create 8x8
//size of canvas - it will consist the padding around the grid from all sides + the grid itself. it's a total sum
var cw = bw + pW;
var ch = bh + pH;
var canvas = $('<canvas/>').attr({width: cw, height: ch}).appendTo('body');
var context = canvas.get(0).getContext("2d");
function drawBoard(){
for (var x = 0; lLimit <= 8; x += bw / 8) { //handling the height grid
context.moveTo(x, 0);
context.lineTo(x, bh);
lLimit++;
}
for (var x = 0; lLimit <= 17; x += bh / 8) { //handling the width grid
context.moveTo(0, x); //begin the line at this cord
context.lineTo(bw, x); //end the line at this cord
lLimit++;
}
//context.lineWidth = 0.5; what should I put here?
context.strokeStyle = "black";
context.stroke();
}
drawBoard();
Run Code Online (Sandbox Code Playgroud)
现在,我成功地使每个屏幕分辨率缩放级别的画布处于相同的比例级别。这是我正在努力实现的目标的一部分。我还尝试实现细线,在所有不同的缩放级别下看起来都相同,当然还可以消除模糊。现在线条的粗细根据缩放级别而变化,有时会变得模糊。
这是 jsFiddle(虽然 jsFiddle 窗口本身很小,所以你几乎不会注意到区别):
https://jsfiddle.net/wL60jo5n/
帮助将不胜感激。
为防止模糊,您应该window.devicePixelRatio在设置canvas元素尺寸时考虑(当然,并在后续绘图期间考虑该尺寸)。
width元素的height属性和属性的canvas值应按比例高于同名 CSS 属性中的值。这可以表示为例如以下函数:
function setCanvasSize(canvas, width, height) {
var ratio = window.devicePixelRatio,
style = canvas.style;
style.width = '' + (width / ratio) + 'px';
style.height = '' + (height / ratio) + 'px';
canvas.width = width;
canvas.height = height;
}
Run Code Online (Sandbox Code Playgroud)