在JavaScript画布中绘制的矩形保持重叠

时间:2013-01-14 10:50:56

标签: javascript canvas

我正在尝试通过在画布上下文中使用fillRect和strokeRect绘制一堆矩形来在JavaScript中创建一个简单的GUI界面。为了弄清楚矩形的大小,我有一个表达式,它占用浏览器窗口中的可用空间并计算每个矩形的坐标。 奇怪的是,即使坐标不相交(我通过输出坐标值来检查) - 矩形也是如此。 这是代码:

var canvas = $("#canvas")[0];
var ctx = canvas.getContext("2d");

var w; 
var h;
var sectionH;
var sectionW;
var sectionX;
var noOfSections;
var gap;
var sectionColor;
var firstY;

//separate sections to follow:
//sessions
var sessionsStartY;
var sessionsEndY;

//activities values
var activitiesStartY;
var activitiesEndY;

//schools values
var schoolsStartY;
var schoolsEndY;

//data entry values
var daenStartY;
var daenEndY;

//general value setup
function generalSetUp() {

    noOfSections = 4;

    ctx.canvas.width = window.innerWidth - 15;
    ctx.canvas.height = window.innerHeight + 500;

    //section edge color and width
    ctx.strokeStyle = "white";
    ctx.lineWidth = 1;

    w = $("#canvas").width();
    h = $("#canvas").height();

    //gap between the sections should vary depending on screen size, 
    //one percent of the whole screen height should do
    //we want the numbers nice and round, hence parseInt
    gap = 15;
    sectionX = 5;
    firstY = 5;
    sectionColor = "rgba(240, 237, 238, 0.5)";

    //we want to fit all the sections on the screen without scrolling, so a bit of calculation is needed to get the
    //height of the section: total height minus top gap, minus bottom gap, minus all the gaps between the sections
    //divided by the total number of sections should give us the height of every section        
    sectionH = ((((h - firstY) - firstY) - (gap * (noOfSections-1))) / noOfSections);
    sectionH = parseInt(sectionH);
    //total available width minus left gap and right gap
    sectionW = ((w - sectionX) - sectionX);
    sectionW = parseInt(sectionW);

    titleFont = gap + 18 + "px Calibri";
    buttonFont = gap + 12 + "px Calibri";
}

//setup for values representing positions of each section
function sectionsSetUp() {
    //section values
    sessionsStartY = firstY;
    sessionsEndY = sessionsStartY + sectionH;

    //activities values
    activitiesStartY = sessionsEndY + gap;
    activitiesEndY = activitiesStartY + sectionH;

    //schools values
    schoolsStartY = activitiesEndY + gap;
    schoolsEndY = schoolsStartY + sectionH;

    //data entry values
    daenStartY = schoolsEndY + gap;
    daenEndY = daenStartY + sectionH;
}

平均剖面图代码如下所示:

//drawing each session: 
function createSessionsSection(sStartX, sStartY, sEndX, sEndY) {
    ctx.fillStyle=sectionColor;
    ctx.strokeStyle = "white";
    ctx.fillRect(sStartX, sStartY, sEndX, sEndY);
    ctx.strokeRect(sStartX, sStartY, sEndX, sEndY);
}

看来第一个和第二个区块之间的差距是15,第二个差距是0,第三个区间看起来像-15,还有一些重叠与fillRects相关。我无法弄清楚造成这种情况的原因。 这是一个截图:

screenshot

0 个答案:

没有答案