<分区>
标签 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/