javascript - Canvas 显示奇怪

标签 javascript css html canvas

我有一个 javascript 程序,它利用 Canvas 在屏幕上显示一些矩形。当我在我的 ChromeBook 上运行它时(将文件保存到 Google Drive 并下载)我在一些方 block 之间有一个空格:

enter image description here

但是,当我在 fiddle 上运行它时:

enter image description here

这是 javascript 部分:

var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight-50;
var charh = charw = 80;
function drawRect(x, y, height, width, color){
    ctx.fillStyle = color;
    ctx.beginPath();
    ctx.fillRect(x, y, width, height);
    ctx.fill();
}
function Archer(x, y){
    this.x = x;
    this.y = y;
    this.draw = function (){
        updatePlayer(this.x+10, this.y, '#3B1000');
        updatePlayer(this.x+15, this.y, '#3B1000');
        updatePlayer(this.x+20, this.y, '#3B1000');
        updatePlayer(this.x+5, this.y+5, '#A56122');
        updatePlayer(this.x+10, this.y+5, '#A56122');
        updatePlayer(this.x+15, this.y+5, '#A56122');
        updatePlayer(this.x+20, this.y+5, '#A56122');
        updatePlayer(this.x+25, this.y+5, '#A56122');
        updatePlayer(this.x+5, this.y+10, '#A56122');
        updatePlayer(this.x+15, this.y+10, '#A56122');
        updatePlayer(this.x+25, this.y+10, '#A56122');
        updatePlayer(this.x+5, this.y+15, '#A56122');
        updatePlayer(this.x+10, this.y+15, '#A56122');
        updatePlayer(this.x+15, this.y+15, '#A56122');
        updatePlayer(this.x+20, this.y+15, '#A56122');
        updatePlayer(this.x+25, this.y+15, '#A56122');
        updatePlayer(this.x+15, this.y+20, '#A56122');
        updatePlayer(this.x+10, this.y+10, '#FFFFFF');
        updatePlayer(this.x+20, this.y+10, '#FFFFFF');
    }
}
var myarcher = new Archer(canvas.width/2-charw/2, canvas.height/2-charh/2);
function update() {                
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    myarcher.draw();
    setTimeout(update, 10);
}
function updatePlayer(x, y, color){
    ctx.fillStyle = color;
    ctx.beginPath();
    ctx.fillRect(x, y, 5, 5);
    ctx.fill();
}
update();

最佳答案

线条是由在非整数像素边界上绘制引起的。您可以将浏览器水平或垂直调整 1 个像素,以根据高度/宽度是偶数还是奇数来查看线条的出现或消失。

试试这个:

var myarcher = new Archer(Math.round(canvas.width/2-charw/2), Math.round(canvas.height/2-charh/2));

关于javascript - Canvas 显示奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28623797/

相关文章:

html - 将背景图像应用于垂直子菜单

html - Twitter Bootstrap 3.3.5 navbar 下拉右拉

html - 将 pdf、doc、ppt 转换为 html5

javascript - Gulp 4.browser-sync的问题//下面的任务没有完成 : browser-sync

javascript - 如何暂停/停止播放音频并替换为新的音频文件

html - css 负背景位置或替代方案?

javascript - Rx DebounceTime 不起作用

php - 术语突出显示算法 (HTML)

javascript - 使用 Angular 从 JSON 调用单个结果

javascript - 获取 M1 Mac 的真实架构,无论 Rosetta