HTML5画布绘制时显示线条

huangapple go评论63阅读模式
英文:

HTML5 canvas Showing lines when drawing

问题

我在绘制瓷砖地图并将瓷砖宽度设置为$(window).width() / 10和瓷砖高度设置为$(window).height() / 10时遇到了问题。

画布在每个瓷砖之间绘制了额外的线条。

这是代码:https://jsfiddle.net/t68sgrf3/

英文:

I have a Problem when drawing tile-map and setting the tile width to $(window).width() / 10 and the tile height to $(window).height() / 10

The canvas drawing additional lines between every tile

Here's the code: <https://jsfiddle.net/t68sgrf3/>

答案1

得分: 0

这是一个带有500x503尺寸画布的示例。请注意,高度不能被10整除,因此我们会看到背景中不正确的水平线穿过。而宽度可以被10整除,因此我们不会看到这样的垂直线。

<canvas width=500 height=503></canvas>
let canvas = document.querySelector('canvas');
let ctx = canvas.getContext("2d");

let width = canvas.width / 10;
let height = canvas.height / 10;
console.log(width, height);

ctx.fillStyle = '#000';
ctx.fillRect(0, 0, canvas.width, canvas.height);

for (let x = 0; x < 10; x++)
  for (let y = 0; y < 10; y++) {
    ctx.fillStyle = (x + y) % 2 ? '#ffe' : '#eef';
    ctx.fillRect(x * width, y * height, width, height);
  }
canvas {
  outline: 1px solid;
}
英文:

Here is an example with a canvas of 500x503 dimensions. Notice the height is not divisible by 10, so we get incorrect horizontal lines of the background showing through. Whereas the width is divisible by 10, and we see no such vertical lines.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let canvas = document.querySelector(&#39;canvas&#39;);
let ctx = canvas.getContext(&quot;2d&quot;);

let width = canvas.width / 10;
let height = canvas.height / 10;
console.log(width, height);

ctx.fillStyle = &#39;#000&#39;;
ctx.fillRect(0, 0, canvas.width, canvas.height);

for (let x = 0; x &lt; 10; x++)
  for (let y = 0; y &lt; 10; y++) {
    ctx.fillStyle = (x + y) % 2 ? &#39;#ffe&#39; : &#39;#eef&#39;;
    ctx.fillRect(x * width, y * height, width, height);
  }

<!-- language: lang-css -->

canvas {
  outline: 1px solid;
}

<!-- language: lang-html -->

&lt;canvas width=500 height=503&gt;&lt;/canvas&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2020年1月4日 01:04:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/59582502.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定