简体   繁体   English

如何制作一个动态画布/网格/行/列,可以调整到浏览器的宽度和高度,同时保持纵横比?

[英]How to make a dynamic canvas/grid/row/column that will adjust to browser width and height, while keeping aspect ratio?

I am really new to javascript, css, and html, but i want to learn.我对 javascript、css 和 html 真的很陌生,但我想学习。 The problem is, its not clear the direction i should head in. I want to make a game site that can play a few games.问题是,我应该朝哪个方向发展还不清楚。我想做一个可以玩几款游戏的游戏网站。 Im trying to make a game board that will have a dynamic size based on the height and/or width of the browser while maintaining the aspect ratio of its original.我试图制作一个具有基于浏览器高度和/或宽度的动态尺寸的游戏板,同时保持其原始纵横比。 It is going to have elements inside of it which must also decrease their size proportionately to its parent.它将在其中包含元素,这些元素也必须与其父级成比例地减小它们的大小。 I have tried using bootstrap 4, with its col, row, and container classes.我曾尝试使用 bootstrap 4 及其 col、row 和 container 类。 I am struggling to make it work with the container class.我正在努力使其与容器类一起工作。 I have recently come across the , which I saw someone use to achieve this.我最近遇到了 ,我看到有人用它来实现这一目标。 can anyone give me a better idea whats going on here?谁能给我一个更好的主意这里发生了什么?

one example is this website https://colonist.io/ just click play game, at the top, manipulate the browser height and width, you will see how it resizes, and all child elements.一个例子是这个网站https://colonist.io/只需点击玩游戏,在顶部,操纵浏览器的高度和宽度,您将看到它如何调整大小,以及所有子元素。 this is the exact effect i am looking for.这是我正在寻找的确切效果。 thanks.谢谢。

Well.. maybe this will suit your needs better好吧..也许这会更适合您的需求

var scale = {}, isInitial = true;

window.onresize = function() {
    // make sure the ctx variable is global or visible in current scope in your code
    ctx.canvas.width = window.innerWidth;
    ctx.canvas.height = window.innerHeight;
    if (isInitial) {
       isInitial = false;
       scale.width = ctx.canvas.width;
       scale.height = ctx.canvas.height;
    } else {
       scale.x = window.innerWidth / scale.width, scale.y = window.innerHeight / scale.height;
       ctx.scale(scale.x, scale.y);

       // redraw your canvas graphics 
    }
}

Please ensure that:请确保:

  • Your canvas position id fixed您的画布位置 ID 已fixed
  • Canvas top and left properties set to 0画布topleft属性设置为 0
  • ctx variable is globally accessible ctx变量是全局可访问的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM