2015-08-20 3 views
1

У меня есть холст, настроенный на моей веб-странице с запущенной в нем анимацией js, которая заполняет все окно браузера, но когда я изменяю размер окна, я не могу получить холст для автоматического изменения размера, чтобы он соответствовал новому размеру окна. Может ли кто-нибудь сказать мне, что мне нужно добавить в мой js, чтобы правильно выполнить эту функцию? Благодаря!Получите Canvas для динамического изменения размера при изменении размера окна браузера

var canvas = document.getElementById('canvas'); 
 
var makecodeplay = canvas.getContext('2d'); 
 
canvas.width=window.innerWidth; 
 
canvas.height=window.innerHeight; 
 

 
makecodeplay.clearRect(0, 0, canvas.width, canvas.height); 
 
makecodeplay.fillStyle = "rgb(75,77,81)"; 
 
makecodeplay.fillRect(0, 0, canvas.width, canvas.height); 
 

 
function randomPaint(inX, inY) { 
 
    
 
    var x = Math.floor(Math.random() * canvas.width); 
 
    var y = Math.floor(Math.random() * canvas.height); 
 
    var r, g, b; 
 
    r = Math.floor(Math.random() * 255); 
 
    g = Math.floor(Math.random() * 255); 
 
    b = Math.floor(Math.random() * 255); 
 
    makecodeplay.beginPath(); 
 
    makecodeplay.fillStyle = "rgba(35,37,41,0.3)"; 
 
    makecodeplay.fillRect(0, 0, canvas.width, canvas.height); 
 
    makecodeplay.fill(); 
 
    makecodeplay.closePath(); 
 

 
    makecodeplay.beginPath(); 
 
    makecodeplay.strokeStyle = "rgba(" + r + "," + g + "," + b + ",0.1)"; 
 
    makecodeplay.lineWidth = 10; 
 
    makecodeplay.moveTo(inX, inY); 
 
    makecodeplay.lineTo(x, y); 
 
    makecodeplay.stroke(); 
 
    makecodeplay.closePath(); 
 

 
    makecodeplay.beginPath(); 
 
    makecodeplay.strokeStyle = "rgba(" + r + "," + g + "," + b + ",0.1)"; 
 
    makecodeplay.lineWidth = 4; 
 
    makecodeplay.moveTo(inX, inY); 
 
    makecodeplay.lineTo(x, y); 
 
    makecodeplay.stroke(); 
 
    makecodeplay.closePath(); 
 

 
    makecodeplay.beginPath(); 
 
    makecodeplay.strokeStyle = "rgb(" + r + "," + g + "," + b + ")"; 
 
    makecodeplay.lineWidth = 1; 
 
    makecodeplay.moveTo(inX, inY); 
 
    makecodeplay.lineTo(x, y); 
 
    makecodeplay.stroke(); 
 
    makecodeplay.closePath(); 
 
     
 
    setTimeout(function() { 
 
     randomPaint(x, y) 
 
    }, 100); 
 
} 
 

 
randomPaint(1, 1);
  
 

 
html, body { 
 
\t margin: 0; 
 
\t padding: 0; 
 
\t width: 100%; 
 
\t height: 100%; 
 
} 
 

 
html { 
 
\t background-color: "#555761"; 
 
\t background: "#555761"; 
 
} 
 

 
body { 
 
\t font-family: "brandon-grotesque"; 
 
\t font-wieght: 100; 
 
\t font-style: normal; 
 
\t color: #656771; 
 
\t bgcolor: "#555761"; 
 
} 
 

 
p { 
 
\t font-family: "brandon-grotesque"; 
 
\t font-wieght: 100; 
 
\t font-style: normal; 
 
\t color: #656771; 
 
} 
 

 
a { 
 
\t color: #555761; 
 
} 
 

 
a:link { 
 
\t color: #555761; 
 
\t text-decoration: none; 
 
} 
 

 
a:visited { 
 
\t color: #555761; 
 
\t text-decoration: none; 
 
} 
 

 
a:hover { 
 
\t color: #656771; 
 
\t text-decoration: none; 
 
} 
 

 
a:active { 
 
\t color: #555761; 
 
\t text-decoration: none; 
 
} 
 

 
/* Auto center content in window */ 
 
#stage { 
 
\t width:100%; 
 
\t margin: 0 auto; 
 
\t padding: 0; 
 
\t } 
 

 
#stage canvas, #overlay { 
 
\t position: absolute; 
 
\t margin: 0 auto; 
 
\t padding: 0; 
 
\t } 
 

 
#overlay { 
 
\t margin: 0 auto; 
 
\t padding: 0; 
 
} 
 

 
#overlay p { 
 
\t color: #333; 
 
\t font-family: "museo-sans"; 
 
\t font-weight: 900; 
 
\t font-style: normal; 
 
\t font-size: 14px; 
 
} 
 

 
.centered { 
 
\t position: fixed; 
 
\t top: 50%; 
 
\t left: 50%; 
 
\t transform: translate(-50%, -50%); 
 
\t -webkit-transform: translate(-50%, -50%); 
 
\t } 
 

 
.centered-bottom { 
 
\t position: fixed; 
 
\t bottom: 3%; 
 
\t left: 50%; 
 
\t transform: translate(-50%, -0%); 
 
\t -webkit-transform: translate(-50%, -50%); 
 
}
<!DOCTYPE html> 
 
<!--[if lt IE 7]>  <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> 
 
<!--[if IE 7]>   <html class="no-js lt-ie9 lt-ie8"> <![endif]--> 
 
<!--[if IE 8]>   <html class="no-js lt-ie9"> <![endif]--> 
 
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> 
 
    <head> 
 
     <meta charset="utf-8"> 
 
     <meta http-equiv="X-UA-Compatible" content="IE=edge"> 
 
     <title>MAKECODEPLAY</title> 
 
     <meta name="description" content=""> 
 
     <meta name="viewport" content="width=device-width, initial-scale=1"> 
 

 
\t \t <script src="//use.typekit.net/uwk8rac.js"></script> 
 
\t \t <script>try{Typekit.load({ async: true });}catch(e){}</script> 
 

 
    </head> 
 
    <body> 
 
     
 
     <div id="stage"> 
 
\t \t \t <canvas id="canvas"></canvas> 
 
\t \t \t <div class="centered"> 
 
\t \t \t \t <img src="img/makecodeplay-logo.png" alt="MAKECODEPLAY" height="70" width="771"></div> 
 
\t \t \t <div class="centered" style="margin-top:50px;"> 
 
\t \t \t \t <p>SITE COMING SOON</p></div> 
 
\t \t \t <div class="centered-bottom"> 
 
\t \t \t \t <footer> 
 
    \t \t \t \t \t <small>&copy; Copyright 2015, MAKECODEPLAY</small> 
 
\t \t \t \t </footer> 
 
\t \t \t </div> 
 
\t \t </div> 
 
    </body> 
 
</html>

ответ

4

Это решение имеет фликкер влияние на изменение размера, но она хорошо выглядит в любом размере.

Полностью используя JQuery в изменении ширины/высоты, он избавился от мерцания. Вот улучшенная версия:

JS:

$(function(){ 
    resizeCanvas(); 
}); 

$(window).on('resize', function(){ 
    resizeCanvas(); 
}); 

function resizeCanvas() 
{ 
    var canvas = $('#canvas'); 
    canvas.css("width", $(window).width()); 
    canvas.css("height", $(window).height()); 
} 

JSFiddle

Причина использования JQuery вместо обычного CSS является то, что фон холст абсолютно позиционирован.

JQuery hack не предпочтительнее, если вам это поможет, но это кажется лучшим выбором для этой ситуации.

+1

Ничего, я не видел включение для jQuery, но, возможно, переключился на $ ('# canvas') [0], чтобы оставаться однородным :) – TOAOGG

+1

@TOAOGG Хорошая идея.Мог бы также изо всех сил с JQuery, хотя на тот момент. с .css() и всеми. Я добавлю это. –

+0

Будьте осторожны, разница между холстом witdth и canvas.style.width Я верю. Это сообщение на это: http://stackoverflow.com/questions/2588181/canvas-is-stretched-when-using-css-but-normal-with-width-height-properties Ширина холста описывает размер окна просмотра, атрибуты css описывают размер скомпонованного элемента в render-dom. – TOAOGG

2

Это регулирует разрешение холста. canvas.width = window.innerWidth; canvas.height = window.innerHeight;

Добавить ширину стилей: 100% и высота: 100% для класса холста, чтобы сделать холст полной шириной и высотой.

var canvas = document.getElementById('canvas'); 
 
      var makecodeplay = canvas.getContext('2d'); 
 
      canvas.width=window.innerWidth; 
 
      canvas.height=window.innerHeight; 
 

 
      makecodeplay.clearRect(0, 0, canvas.width, canvas.height); 
 
      makecodeplay.fillStyle = "rgb(75,77,81)"; 
 
      makecodeplay.fillRect(0, 0, canvas.width, canvas.height); 
 

 
      function randomPaint(inX, inY) { 
 

 
       var x = Math.floor(Math.random() * canvas.width); 
 
       var y = Math.floor(Math.random() * canvas.height); 
 
       var r, g, b; 
 
       r = Math.floor(Math.random() * 255); 
 
       g = Math.floor(Math.random() * 255); 
 
       b = Math.floor(Math.random() * 255); 
 
       makecodeplay.beginPath(); 
 
       makecodeplay.fillStyle = "rgba(35,37,41,0.3)"; 
 
       makecodeplay.fillRect(0, 0, canvas.width, canvas.height); 
 
       makecodeplay.fill(); 
 
       makecodeplay.closePath(); 
 

 
       makecodeplay.beginPath(); 
 
       makecodeplay.strokeStyle = "rgba(" + r + "," + g + "," + b + ",0.1)"; 
 
       makecodeplay.lineWidth = 10; 
 
       makecodeplay.moveTo(inX, inY); 
 
       makecodeplay.lineTo(x, y); 
 
       makecodeplay.stroke(); 
 
       makecodeplay.closePath(); 
 

 
       makecodeplay.beginPath(); 
 
       makecodeplay.strokeStyle = "rgba(" + r + "," + g + "," + b + ",0.1)"; 
 
       makecodeplay.lineWidth = 4; 
 
       makecodeplay.moveTo(inX, inY); 
 
       makecodeplay.lineTo(x, y); 
 
       makecodeplay.stroke(); 
 
       makecodeplay.closePath(); 
 

 
       makecodeplay.beginPath(); 
 
       makecodeplay.strokeStyle = "rgb(" + r + "," + g + "," + b + ")"; 
 
       makecodeplay.lineWidth = 1; 
 
       makecodeplay.moveTo(inX, inY); 
 
       makecodeplay.lineTo(x, y); 
 
       makecodeplay.stroke(); 
 
       makecodeplay.closePath(); 
 

 
       setTimeout(function() { 
 
        randomPaint(x, y) 
 
       }, 100); 
 
      } 
 

 
      randomPaint(1, 1);
html, body { 
 
       margin: 0; 
 
       padding: 0; 
 
       width: 100%; 
 
       height: 100%; 
 
      } 
 

 
      html { 
 
       background-color: "#555761"; 
 
       background: "#555761"; 
 
      } 
 

 
      body { 
 
       font-family: "brandon-grotesque"; 
 
       font-wieght: 100; 
 
       font-style: normal; 
 
       color: #656771; 
 
       bgcolor: "#555761"; 
 
      } 
 

 
      p { 
 
       font-family: "brandon-grotesque"; 
 
       font-wieght: 100; 
 
       font-style: normal; 
 
       color: #656771; 
 
      } 
 

 
      a { 
 
       color: #555761; 
 
      } 
 

 
      a:link { 
 
       color: #555761; 
 
       text-decoration: none; 
 
      } 
 

 
      a:visited { 
 
       color: #555761; 
 
       text-decoration: none; 
 
      } 
 

 
      a:hover { 
 
       color: #656771; 
 
       text-decoration: none; 
 
      } 
 

 
      a:active { 
 
       color: #555761; 
 
       text-decoration: none; 
 
      } 
 

 
      /* Auto center content in window */ 
 
      #stage { 
 
       width:100%; 
 
       margin: 0 auto; 
 
       padding: 0; 
 
       } 
 

 
      #stage canvas, #overlay { 
 
       position: absolute; 
 
       margin: 0 auto; 
 
       padding: 0; 
 
       } 
 

 
      #overlay { 
 
       margin: 0 auto; 
 
       padding: 0; 
 
      } 
 

 
      #overlay p { 
 
       color: #333; 
 
       font-family: "museo-sans"; 
 
       font-weight: 900; 
 
       font-style: normal; 
 
       font-size: 14px; 
 
      } 
 

 
      .centered { 
 
       position: fixed; 
 
       top: 50%; 
 
       left: 50%; 
 
       transform: translate(-50%, -50%); 
 
       -webkit-transform: translate(-50%, -50%); 
 
       } 
 

 
      .centered-bottom { 
 
       position: fixed; 
 
       bottom: 3%; 
 
       left: 50%; 
 
       transform: translate(-50%, -0%); 
 
       -webkit-transform: translate(-50%, -50%); 
 
      }
<script src="//use.typekit.net/uwk8rac.js"></script> 
 
     <script>try{Typekit.load({ async: true });}catch(e){}</script> 
 

 
     
 
    
 
     <!--[if lt IE 7]> 
 
      <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p> 
 
     <![endif]--> 
 

 
     <div id="stage"> 
 
      <canvas id="canvas" style="width:100%; height:100%;"></canvas> 
 
      <div class="centered"> 
 
       <img src="img/makecodeplay-logo.png" alt="MAKECODEPLAY" height="70" width="771"></div> 
 
      <div class="centered" style="margin-top:50px;"> 
 
       <p>SITE COMING SOON</p></div> 
 
      <div class="centered-bottom"> 
 
       <footer> 
 
        <small>&copy; Copyright 2015, MAKECODEPLAY</small> 
 
       </footer> 
 
      </div> 
 
     </div>

+0

я понял, почему это решение является расплывчатым. Это именно потому, что вы прокомментировали canvas.width = window.innerWidth; canvas.height = window.innerHeight ;. Вам нужно увеличить его высоту и ширину, чтобы разрешение совпало. [Так вы это сделаете] (http://stackoverflow.com/a/21325438/2283050). Исправьте свой ответ, и я добавлю в заметку о себе, чтобы увидеть вашу, так как это меньше взломать. –

1

Существует обработчик событий для окна обнаружения изменяет размеры: https://developer.mozilla.org/de/docs/Web/API/GlobalEventHandlers/onresize

так что вы могли бы сделать что-то вроде

window.onResize = function() 
{ 
    var canvas = document.getElementById('canvas'); 
    canvas.width = window.innerWidth; 
    canvas.style.width = window.innerWidth; 
    canvas.height = window.innerHeight; 
    canvas.style.height = window.innerHeight; 
} 
-1

Это есть ответ https://stackoverflow.com/a/7863738/1619663

Попробуйте установить размеры холста к размеры экрана, а не размеры окна.

т.е.

canvas.width=screen.width; 
canvas.height=screen.height; 

См JSFiddle: https://jsfiddle.net/rjgunning/wLbzv7e0/

+0

Ссылка хорошая, но ваше решение на самом деле не изменяет размер холста. – TOAOGG

+0

А, извините, я только что проверил это в jsfiddle. он изменил размер, но я не смотрел внимательно – rgunning

Смежные вопросы