我有以下坐标网格:jsfiddle.net/b6pwrrca/29
如何更改尺寸,以便x轴从-7到7,例如,y轴从-5到12?
我在下面发布了我认为相关的代码:
static belongsTo = [author: Author]
答案 0 :(得分:1)
以下是如何绘制可调整大小的网格
首先设置一些最小值和最大值:
var minX=-7;
var maxX=7;
var minY=-5;
var maxY=12;
计算将在网格中的行数
var vlines=maxX-minX;
var hlines=maxY-minY;
计算宽度&每个网格单元的高度
var cellwidth=canvasWidth/vlines;
var cellheight=canvasHeight/hlines;
现在您可以像这样绘制网格线:
function drawGrid(){
var midYY=midY*cellheight;
var midXX=midX*cellwidth;
ctx.font='12px verdana';
ctx.lineWidth=1;
ctx.globalAlpha=0.50;
ctx.beginPath();
// draw vertical X lines
for(var n=1;n<vlines;n++){
var x=parseInt(n*cellwidth);
ctx.moveTo(x,0);
ctx.lineTo(x,ch);
if(n<vlines && minX+n!==0){ ctx.fillText(minX+n,x,midYY-cellheight/2); }
}
// draw horizontal Y lines
for(var n=1;n<hlines;n++){
var y=parseInt(n*cellheight);
ctx.moveTo(0,y);
ctx.lineTo(cw,y);
if(n<hlines && maxY-n!==0){ ctx.fillText(maxY-n,midXX+cellwidth/2,y); }
}
ctx.stroke();
ctx.globalAlpha=1.00;
// draw darker origin lines
ctx.beginPath();
ctx.moveTo(midXX,0);
ctx.lineTo(midXX,ch);
ctx.moveTo(0,midYY);
ctx.lineTo(cw,midYY);
ctx.lineWidth=3;
ctx.stroke();
}
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
// declare mins & maxes
var minX=-7;
var maxX=7;
var minY=-5;
var maxY=12;
var midX=7;
var midY=12;
// calc # lines in grid
var vlines=maxX-minX;
var hlines=maxY-minY;
// calc cell sizes
var cellwidth=cw/vlines;
var cellheight=ch/hlines;
// context styling
ctx.textAlign='center';
ctx.textBaseline='middle';
// sharpen the lines
ctx.translate(0.50,0.50);
// go draw stuff
drawGrid();
drawPoint(-4,3);
function drawGrid(){
var midYY=midY*cellheight;
var midXX=midX*cellwidth;
ctx.font='12px verdana';
ctx.lineWidth=1;
ctx.globalAlpha=0.50;
ctx.beginPath();
// draw vertical X lines
for(var n=1;n<vlines;n++){
var x=parseInt(n*cellwidth);
ctx.moveTo(x,0);
ctx.lineTo(x,ch);
if(n<vlines && minX+n!==0){ ctx.fillText(minX+n,x,midYY-cellheight/2); }
}
// draw horizontal Y lines
for(var n=1;n<hlines;n++){
var y=parseInt(n*cellheight);
ctx.moveTo(0,y);
ctx.lineTo(cw,y);
if(n<hlines && maxY-n!==0){ ctx.fillText(maxY-n,midXX+cellwidth/2,y); }
}
ctx.stroke();
ctx.globalAlpha=1.00;
// draw darker origin lines
ctx.beginPath();
ctx.moveTo(midXX,0);
ctx.lineTo(midXX,ch);
ctx.moveTo(0,midYY);
ctx.lineTo(cw,midYY);
ctx.lineWidth=3;
ctx.stroke();
}
// draw a point
function drawPoint(x,y){
var xx=(x-minX)*cellwidth;
var yy=(y-minY)*cellheight;
var yy=(maxY-y)*cellheight;
ctx.font='10px verdana';
ctx.beginPath();
ctx.arc(xx,yy,4,0,Math.PI*2);
ctx.fillStyle='red';
ctx.fill();
ctx.fillText('('+x+','+y+')',xx,yy-10);
}
body{ background-color:white; }
#canvas{border:1px solid red; }
<canvas id="canvas" width=400 height=400></canvas>