Создание координатной сетки с помощью
Координатная сетка очень помогает при вёрстке. Позволяет увидеть, как будут выглядеть те или иные элементы при их создании и позиционировании относительно границ.
Для SVG была разработана такая адаптивная координатная сетка :
function changeHeight() {
itrX.addEventListener("input",()=>{svg.setAttribute("height",itrX.value)});
var x = document.getElementById("itrX").value;
document.getElementById("infoX").innerHTML = "SVG height: " + x +"px";
}
function changeWidth() {
itrY.addEventListener("input",()=>{svg.setAttribute("width",itrY.value)});
var x = document.getElementById("itrY").value;
document.getElementById("infoY").innerHTML = "SVG width: " + x +"px";
}
<style>
text {
font-size:20px;
fill:black;
}
p {
display:inline-block;
font-weight:bold;
margin: 1em ;
}
</style>
<p id="infoX" ></p>
<p id="infoY" ></p>
<div>
<span><input id="itrX" type="range" min="10" max="1000" value="1000" oninput="changeHeight()"/></span>
<span><input id="itrY" type="range" min="10" max="1000" value="1000" oninput="changeWidth()"/></span>
</div>
<svg id="svg" width="1000" height="1000" viewBox="-20 -20 1050 1050" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" style="border:2px solid purple">
<defs>
<pattern id="p10" width="10" height="10" patternUnits="userSpaceOnUse">
<path d="M 10 0 L 0 0 0 10" fill="none" stroke="gray" stroke-width="0.5"/>
</pattern>
<pattern id="p100" width="100" height="100" patternUnits="userSpaceOnUse">
<rect width="100" height="100" fill="url(#p10)"/>
<path d="M 100 0 L 0 0 0 100" fill="none" stroke="gray" stroke-width="1"/>
</pattern>
</defs>
<rect width="1000" height="1000" fill="url(#p100)" />
<circle cx="500" cy="500" r="5" fill="black" />
<!-- Вертикальный блок цифр -->
<text x="-15" y="0">0,0</text>
<text x="-20" y="100" >100</text>
<text x="-20" y="200">200</text>
<text x="-20" y="300">300</text>
<text x="-20" y="400">400</text>
<text x="-20" y="500">500</text>
<text x="-20" y="600">600</text>
<text x="-20" y="700">700</text>
<text x="-20" y="800">800</text>
<text x="-20" y="900">900</text>
<text x="-20" y="1000">1000</text>
<!-- Горизонтальный блок -->
<text x="100" y="-5" >100</text>
<text x="200" y="-5" >200</text>
<text x="300" y="-5">300</text>
<text x="400" y="-5">400</text>
<text x="500" y="-5">500</text>
<text x="600" y="-5">600</text>
<text x="700" y="-5">700</text>
<text x="800" y="-5">800</text>
<text x="900" y="-5">900</text>
<text x="990" y="-5">1000</text>
<!-- Ракета -->
<g transform="scale(1)" fill="purple">
<path d="m308.167 241.52c0-28.766-23.403-52.169-52.17-52.169s-52.17 23.403-52.17 52.169c0 28.767 23.403 52.17 52.17 52.17s52.17-23.404 52.17-52.17zm-52.169 22.169c-12.225 0-22.17-9.945-22.17-22.17 0-12.224 9.945-22.169 22.17-22.169s22.17 9.945 22.17 22.169c-.001 12.225-9.946 22.17-22.17 22.17z"/>
<path d="m425.684 424.352v-132.322l-51.65-32.948c.615-14.332.261-28.762-1.117-43.191-7.162-74.973-41.384-144.771-96.362-196.535l-20.557-19.356-20.558 19.356c-54.978 51.765-89.2 121.563-96.362 196.535-1.378 14.429-1.732 28.859-1.117 43.191l-51.65 32.948v132.321l90.003-28.282c3.744 6.784 7.752 13.436 12.017 19.945v62.315h30v-48.333h22.667v23.252h30v-23.252h22.667v48.333h30v-62.315c4.265-6.508 8.273-13.161 12.017-19.945zm-30-115.874v75.001l-46.66-14.662c10.468-24.35 17.778-49.975 21.762-76.222zm-139.694-267.28c27.301 25.706 48.392 55.971 63.081 88.684h-126.153c14.687-32.713 35.775-62.979 63.072-88.684zm-139.679 342.281v-75.001l24.898-15.883c3.983 26.247 11.293 51.872 21.762 76.222zm124.687-10.983v27.499h-27.316c-47.563-72.299-57.394-161.126-32.242-240.114h149.112c25.156 78.987 15.325 167.815-32.238 240.114h-27.316v-27.499z"/>
<path d="m240.998 483.495h30v28.5h-30z"/>
</g>
</svg>
Другие варианты координатных сеток на CSS, JS: здесь и здесь
Нужен вариант на <canvas> с возможностью масштабирования width и height
Так же очень желательно наличие цифр по краям сетки, как на рисунке ниже:
Буду благодарен за идеи и решения.
Ответы (1 шт):
В canvas масштабирование тонких линий не очень. Здесь попытка составить изображение сетки на бОльшем холсте с переносом на меньший.
Вместо input[type="range"] добавил красный контроллер для изменения ширины и высоты контейнера. Ракеты нет.
const grid = document.querySelector('.grid');
const control = document.querySelector('.grid__controls');
const canvas = document.querySelector('.grid__canvas');
drawGrid(canvas, 1000, 1000, 2200,2200,100,10,10,100);
function drawGrid(canvas, w, h, ...options){
const ctx = canvas.getContext('2d');
canvas.width = w;
canvas.height = h;
ctx.drawImage(getGrid(...options), 0, 0, options[0], options[1], 0,0,w,h);
}
function getGrid(img_w,img_h,cell_num,cell_weight,text_freq,side_w){
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const w = canvas.width = img_w;
const h = canvas.height = img_h;
const cell_size = (img_w-side_w*2)/cell_num;
const x_num = cell_num;
const y_num = (img_h-side_w*2)/cell_size;
ctx.font = `${side_w*1.4/(y_num.toString().length+1)}px monospace`;
let basic_grid_path = '';
let text_grid_path = '';
ctx.save();
ctx.textBaseline = 'bottom';
ctx.textAlign = 'center';
for(let i = 0; i < x_num + 1; i++){
let line = `M ${cell_size*i + side_w} ${side_w} V ${h-side_w}`;
basic_grid_path += line;
if(i%text_freq == 0){
text_grid_path += line;
ctx.fillText(i*cell_weight, cell_size*i + side_w, side_w);
}
}
ctx.restore();
ctx.save();
ctx.textBaseline = 'middle';
ctx.textAlign = 'right';
for(let i = 0; i < y_num + 1; i++){
let line = `M ${side_w} ${cell_size*i + side_w} H ${w-side_w}`;
basic_grid_path += line;
if(i%text_freq == 0){
text_grid_path += line;
ctx.fillText(i*cell_weight + ' ', side_w, cell_size*i + side_w);
}
}
ctx.restore();
ctx.save();
ctx.strokeStyle = 'rgb(100,100,100)';
ctx.stroke(new Path2D(basic_grid_path));
ctx.restore();
ctx.save();
ctx.strokeStyle = 'rgb(50,50,50)';
ctx.lineWidth = 2;
ctx.stroke(new Path2D(text_grid_path));
ctx.restore();
return canvas;
}
let start_point = [0,0];
let is_dragging = false;
control.addEventListener('mousedown', event => {
is_dragging = true;
start_point = [event.pageX, event.pageY];
})
document.addEventListener('mouseup', () => {
is_dragging = false;
})
document.addEventListener('mousemove', event => {
if(is_dragging) resizeGrid(event);
})
function resizeGrid(event){
const x = event.pageX;
const y = event.pageY;
const width = parseFloat(window.getComputedStyle(grid).width);
const height = parseFloat(window.getComputedStyle(grid).height);
grid.style.width = (width - start_point[0] + x) + 'px';
grid.style.height = (height - start_point[1] + y) + 'px';
start_point[0] = x;
start_point[1] = y;
}
.grid {
box-sizing: border-box;
border: 1px solid black;
position: relative;
width: 600px;
height: 600px;
}
.grid__canvas {
max-width: 100%;
max-height: 100%;
}
.grid__controls {
width: 10px;
height: 10px;
background: red;
position: absolute;
bottom: -5px;
right: -5px;
cursor: nw-resize;
}
<div class="grid">
<canvas class="grid__canvas"></canvas>
<div class="grid__controls"></div>
</div>
