【发布时间】:2020-08-22 21:20:49
【问题描述】:
我正在尝试编写一个小的 html5 画布游戏,但在动态背景大小和对象定位方面遇到了一些困难——也许我的想法有点错误,但我希望你能提供帮助。 这是我的代码:
var canvas = document.getElementById("background");
var c = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var background = new Image();
background.src = "https://images.pexels.com/photos/255379/pexels-photo-255379.jpeg";
function scaleToFill(img){
// get the scale
var scale = Math.max(canvas.width / background.width, canvas.height / background.height);
c.drawImage(img, 0, 0, background.width * scale, canvas.height );
}
background.onload = function(){
scaleToFill(this);
c.fillRect(100, 100, 100, 100);
}
body {
margin: 0;
padding: 9;
width: 100%;
height: 100%;
}
canvas {
border:1px solid #000;
}
<canvas id="background" style="z-index: -1; position:fixed; top:0;left:0;">
</canvas>
非常基本 - 我的代码所做的是尝试将背景图片缩放到全高。 现在但是由于这种缩放所有其他元素,比如我绘制的测试矩形根据屏幕尺寸坐在不同的位置。
有谁知道我如何在没有静态高度和宽度的情况下用不同的方法解决这个问题? 或者有没有 js 框架可以更轻松地做到这一点?
【问题讨论】:
标签: javascript css html5-canvas