javascript - Canvas fillRect 高度和宽度总是倾斜/扭曲

标签 javascript css html canvas

<分区>

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

<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>

这是 Canvas 的 CSS:

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

我试过改变一些尺寸,结果还是这样。 我正在测试的浏览器是 Chrome。

最佳答案

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

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

将 Canvas 想象成一幅图像。如果您调整图像的大小,它就会变形。

简单地删除 CSS 样式。

关于javascript - Canvas fillRect 高度和宽度总是倾斜/扭曲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38516589/

上一篇:html - 更改 CSS 类的一部分

下一篇:java - 使用 javaFX 对齐文本时遇到问题

相关文章:

javascript - ng 样式和自定义 css 属性

css - jquery ui拖放效果

jquery - 对来自不同 DIV 的元素进行排序

html - 如何使 flex 元素正确对齐?

javascript - 使用 currentTime 时视频滞后

javascript - 如果未启用 JavaScript,则卡住带有覆盖的屏幕

javascript - 在 JavaScript 中获取页面加载开始时间

javascript - Laravel Mix 网页错误 Linux DEV 或 PROD

javascript - 仅使用 JavaScript 上传进度

html - 每一个下的div