【问题标题】:HTML5 Canvas - dynamic background + element positioningHTML5 Canvas - 动态背景+元素定位
【发布时间】: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


    【解决方案1】:

    一旦你走这条路,一切都必须与宽度和高度成比例或相对...

    请参阅下面的示例,我仍在绘制矩形,就像您使用绝对位置所做的那样
    但我也在画布中间画了一个圆圈。

    如果你正在创建一个游戏,你将不得不做出那些决定什么是相对的,什么不是

    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";
    
    
    background.onload = function(){
      var scale = Math.max(canvas.width / background.width, canvas.height / background.height);
      c.drawImage(this, 0, 0, background.width * scale, canvas.height );
      
      // absolute position
      c.fillRect(10, 10, 50, 50);
      
      // fixed position with relative size 
      c.fillRect(10, 80, 1000*scale, 200*scale);
      
      // relative position with fixed radius
      c.arc(canvas.width/2, canvas.height/2, 50, 0, Math.PI*2);
      c.stroke()
    }
    &lt;canvas id="background"&gt;    &lt;/canvas&gt;

    也许研究一下游戏引擎,那些可以为您节省大量时间:
    https://github.com/collections/javascript-game-engines

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-01
      • 1970-01-01
      • 2013-08-06
      • 1970-01-01
      • 2018-08-21
      • 1970-01-01
      • 2023-03-12
      • 2018-12-29
      相关资源
      最近更新 更多