Почему не работает js в django?

Не работает часть js но при простой верстке всё робетю. Тоесть если я просто напишу html файл и подключу js все работает.
Вот код html: {% load staticfiles %}

<!DOCTYPE html>
<html lang="ru">
<head>
    <title>{% block title %}Недвижимость{% endblock %}</title>
    <meta charset="UTF-8">
    <link rel="stylesheet"  href="{% static 'css/main.css' %}" type="text/css">
    <script src="{% static 'js/main.js' %}"></script>
</head>
<body>
<header id="fixedDiv" class="fixed fixed-top">
  <div class="logotip-sayta">Что-то будет</div>
  <input class="savuden-domekas" id="menu" type="checkbox"/>
  <label class="unclose" for="menu">
  <i class="fa fa-th-list"></i>
  </label>
  <nav>
  <ul id="menu">
      <li><a href="#">Блог</a></li>
      <li><a href="#">Бренды</a></li>
      <li><a href="powerman.html">Энергетики</a></li>
  </ul>
  <label class="veplotnuma" for="menu">
    <i class="fa fa-times-circle"></i>
  </label>
  </nav>
</header>

  <canvas id="canvas"></canvas>


</body>
</html>

Вот js:

setTimeout(function(){
  document.body.classList.add('body_visible');
}, 200); "Плавная загрузка (эта часть работает)"


"Анимация навигационой панели при скроленге верх она появляется а при скролинги в низ проподает"

var oldScrollY = 0;
var div = document.getElementById("fixedDiv");

window.onscroll = function() {
  var scrolled = window.pageYOffset || document.documentElement.scrollTop;
  var dY = scrolled - oldScrollY;

  if ( dY > 0 ){
    div.className = "fixed fixed-bottom";
  } else {
    div.className = "fixed fixed-top";
  }

  oldScrollY = scrolled;
}

"анимаций фона"

let resizeReset = function() {
    w = canvasBody.width = window.innerWidth;"Анимация роботает во всю ширину тега body"
    h = canvasBody.height = window.innerHeight;"Анимация роботает во всю длину тега body"
}



const opts = { 
    particleColor: "rgb(192,192,192)",
    lineColor: "rgb(192,192,192)",
    particleAmount: 60,
    defaultSpeed: 1,
    variantSpeed: 3,
    defaultRadius: 1,
    variantRadius: 1,
    linkRadius: 200,
};"задает характеристики"

window.addEventListener("resize", function(){
    deBouncer();
});

let deBouncer = function() {
    clearTimeout(tid);
    tid = setTimeout(function() {
        resizeReset();
    }, delay);
};

let checkDistance = function(x1, y1, x2, y2){ 
    return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
};

let linkPoints = function(point1, hubs){ 
    for (let i = 0; i < hubs.length; i++) {
        let distance = checkDistance(point1.x, point1.y, hubs[i].x, hubs[i].y);
        let opacity = 1 - distance / opts.linkRadius;
        if (opacity > 0) { 
            drawArea.lineWidth = 0.5;
            drawArea.strokeStyle = `rgba(${rgb[0]}, ${rgb[1]}, ${rgb[2]}, ${opacity})`;
            drawArea.beginPath();
            drawArea.moveTo(point1.x, point1.y);
            drawArea.lineTo(hubs[i].x, hubs[i].y);
            drawArea.closePath();
            drawArea.stroke();
        }
    }
}

Particle = function(xPos, yPos){ 
    this.x = Math.random() * w; 
    this.y = Math.random() * h;
    this.speed = opts.defaultSpeed + Math.random() * opts.variantSpeed; 
    this.directionAngle = Math.floor(Math.random() * 360); 
    this.color = opts.particleColor;
    this.radius = opts.defaultRadius + Math.random() * opts. variantRadius; 
    this.vector = {
        x: Math.cos(this.directionAngle) * this.speed,
        y: Math.sin(this.directionAngle) * this.speed
    };
    this.update = function(){ 
        this.border(); 
        this.x += this.vector.x; 
        this.y += this.vector.y; 
    };
    this.border = function(){ 
        if (this.x >= w || this.x <= 0) { 
            this.vector.x *= -1;
        }
        if (this.y >= h || this.y <= 0) {
            this.vector.y *= -1;
        }
        if (this.x > w) this.x = w;
        if (this.y > h) this.y = h;
        if (this.x < 0) this.x = 0;
        if (this.y < 0) this.y = 0; 
    };
    this.draw = function(){ 
        drawArea.beginPath();
        drawArea.arc(this.x, this.y, this.radius, 0, Math.PI*2);
        drawArea.closePath();
        drawArea.fillStyle = this.color;
        drawArea.fill();
    };
};

function setup(){ 
    particles = [];
    resizeReset();
    for (let i = 0; i < opts.particleAmount; i++){
        particles.push( new Particle() );
    }
    window.requestAnimationFrame(loop);
}

function loop(){ 
    window.requestAnimationFrame(loop);
    drawArea.clearRect(0,0,w,h);
    for (let i = 0; i < particles.length; i++){
        particles[i].update();
        particles[i].draw();
    }
    for (let i = 0; i < particles.length; i++){
        linkPoints(particles[i], particles);
    }
}

const canvasBody = document.getElementById("canvas"),
drawArea = canvasBody.getContext("2d");
let delay = 200, tid,
rgb = opts.lineColor.match(/\d+/g);
resizeReset();
setup();

Вот css:
#canvas {
    width: 100%;
    position: fixed;
    display: block;
    top: 0;
    left: 0;
    z-index: -1;
    }
.fixed-top {
    top: 0;
}

.fixed {
    text-align: center;
    position: fixed;
    z-index: 2;
    -webkit-transition: top .2s ease-out 0s;
    -moz-transition: top .2s ease-out 0s;
    -o-transition: top .2s ease-out 0s;
    transition: top .2s ease-out 0s;
}
header {
    width: 100%;
    background: #161a1e;
    padding: 15px 0;
    margin-bottom: 30px;
    display: flex;
    align-items: center;
    justify-content: space-between; }
  • Вопрос задан
  • 1582 просмотра
Решения вопроса 1
WStanley
@WStanley
Back-end Developer
Uncaught TypeError: Cannot read property 'getContext' of null

Insanus, в canvasBody вы получаете null, а у null нет свойства getContext
const canvasBody = document.getElementById("canvas"),
drawArea = canvasBody.getContext("2d");

Вероятнее всего это потому, что элемента "canvas" в DOM еще не существует, а вы к нему обращаетесь, надо дождаться пока DOM сформируется ссылка1, ссылка2, ссылка3
Либо подключите jquery и оберните код в: ссылка
$( document ).ready(function() {
    console.log( "ready DOM" );
   // ваш код
});

Первое, что стоит попробовать это перенести подключение js кода ниже, но это врятли поможет, надо дождаться формирования DOM
<canvas id="canvas"></canvas>

<script src="{% static 'js/main.js' %}"></script>
</body>
</html>
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 1
dimonchik2013
@dimonchik2013
non progredi est regredi
маловато кода

но если чо, смотрят в
1) логи
2) отладку

а вместо кода можешь Hello Word and World! написать
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы