【问题标题】:Canvas fillRect height and width are always skewed/distorted [duplicate]画布fillRect高度和宽度总是倾斜/扭曲[重复]
【发布时间】:2016-11-25 18:36:52
【问题描述】:

我放在画布上的形状总是以某种方式扭曲。我不确定这是我的画布尺寸还是错误的代码。 (尽管如果它是糟糕的代码,现在可能已经修复了它)。这是我的代码:

<script type = "text/javascript">
var game = document.getElementById("game");
//To keep the shapes from coming out with low resolution/a fuzzy look
game.height = 1000;
game.width = 1000;
var context = game.getContext("2d");
var gamePieces = []
function gamePiece(width, height, color, x, y){
    this.width = width;
    this.height = height;
    this.x = x;
    this.y = y;
    this.update = function(){
        context.fillStyle = color;
        context.fillRect(this.x, this.y, this.height, this.width);
    }
    this.move = function(distancex, distancey, leftOrRight, upOrDown){
        if(leftOrRight.toLowerCase() == "left"){
            this.x = this.x - distancex
        } else if(leftOrRight.toLowerCase() == "right"){
            this.x = this.x + distancex;
        }
        if(upOrDown.toLowerCase() == "up"){
            this.y = this.y - distancey;
        } else if(upOrDown.toLowerCase() == "down"){
            this.y = this.y + distancey
        }
    }
    gamePieces[gamePieces.length] = this
    context.fillStyle = color;
    context.fillRect(this.x, this.y, this.height, this.width);
}
function update(){
    context.clearRect(0, 0, game.width, game.height);
    for(var i = 0; i < gamePieces.length; i++){
        gamePieces[i].update();
    }
}
setInterval(update, 1);
var p1 = new gamePiece(100, 100, "blue", 0, 0);

</script>

这是画布的 CSS:

#game {
    height: 100%;
    width: 100%;
}

我已经尝试改变一些尺寸,但仍然是这样。 我正在测试的浏览器是 Chrome。

【问题讨论】:

  • “不要使用 css 来调整你的画布大小”使用这个作为搜索词,你会找到你的解决方案。

标签: javascript css html canvas


【解决方案1】:

您将画布的宽度和高度设置为 1000 像素,但随后将 css 宽度和高度设置为 100%。

画布仍为 1000*1000 像素,但 CSS 会缩放内容以匹配窗口的纵横比。

将画布想象成一幅图像。如果您调整图像大小,则图像会失真。

只需删除 CSS 样式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-06
    • 2016-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    • 2018-12-22
    相关资源
    最近更新 更多