矩形之间的像素而不是HTML5 Canvas中的绘制线

时间:2019-01-18 14:11:15

标签: javascript html5-canvas

基本上,我希望在rects之间能看到背景。现在,我正在尝试留下一个取决于它们之间的rect大小的距离,我可以将该大小设为精确的像素数吗?

因为现在这些空白合并,有时根本看不到,等等。

function getMousePos(canvas, evt) {
  var rect = canvas.getBoundingClientRect();
  return {
    x: evt.clientX - rect.left,
    y: evt.clientY - rect.top
  };
}

var canvas = document.getElementById("posHourCanvas");
var context = canvas.getContext('2d');

var boxes = [];

function init() {
  context.clearRect(0, 0, canvas.width, canvas.height);
  boxes.length = 0;
  const strokeWidth = 0.2;
  canvas.width = $('#two')[0].clientWidth;
  var cellSize = canvas.width / 27;
  canvas.height = 7 / 27 * canvas.width;
  var x = y = 0;
  draw(x, y, canvas.width, canvas.height, cellSize, strokeWidth);
}

function Box(x, y, day, hour) {
  this.x = x;
  this.y = y;
  this.day = day;
  this.hour = hour;
}

function draw(x, y, w, h, cellSize, strokeWidth) {

  let onePixel = cellSize * strokeWidth;
  cellSize = cellSize * (1 - strokeWidth);
  context.beginPath();
  context.lineWidth = 0.01;
  context.strokeStyle = 'rgba(255, 255, 255, 0)';

  for (let i = 0; i < 7; i++) {
    context.beginPath();
    dayRect(context, cellSize, i, onePixel);
    let startX = 3 * cellSize + onePixel;
    for (let j = 0; j < 25; j++) {
      context.rect(startX, i * cellSize + i * onePixel, cellSize, cellSize);
      context.fillStyle = "white";
      context.fill();
      startX += cellSize + onePixel;
    }
  }
}

function dayRect(context, cellSize, day, onePixel) {
  var offSet = day * onePixel;
  context.rect(0, day * cellSize + offSet, 3 * cellSize, cellSize);
  context.fillStyle = "white";
  context.fill();
}

init();
window.addEventListener("resize", init, false);
body {
  margin: auto;
  color: white;
  background-color: black;
}

div#two {
  margin-left: 5%;
  width: 10%;
  height: 30%;
}
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>

<div id="parent">
  <div>text above</div>

  <div id="two">
    <canvas id="posHourCanvas" width="600" height="300"></canvas>
  </div>

  <div>text under</div>
</div>

JSFIDDLE:http://jsfiddle.net/kgbh9352/

0 个答案:

没有答案