画布显示怪异

时间:2015-02-20 07:37:48

标签: javascript html css html5 canvas

我有一个javascript程序,利用画布在屏幕上显示一些矩形。当我在ChromeBook上运行此文件(将文件保存到Google云端硬盘并下载)时,我会在某些方块之间留出空格:

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 个答案:

答案 0 :(得分:4)

线条是通过绘制非整数像素边界引起的。您可以水平或垂直地将浏览器调整1个像素,以根据高度/宽度是偶数还是奇数来查看线条是否显示。

请改为尝试:

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