I
I
Insanus2020-03-09 21:38:07
Django
Insanus, 2020-03-09 21:38:07

Why doesn't js work in django?

The js part does not work, but with a simple layout, everything is shy. That is, if I just write an html file and connect js, everything works.
Here is the html code: {% 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>

Here is 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();

Here is the 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; }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
WStanley, 2020-03-10
@Insanus

Uncaught TypeError: Cannot read property 'getContext' of null

Insanus , in canvasBody you get null and null has no getContext property
const canvasBody = document.getElementById("canvas"),
drawArea = canvasBody.getContext("2d");

Most likely this is because the "canvas" element does not yet exist in the DOM, and you are accessing it, you need to wait until the DOM is formed link1 , link2 , link3
Or connect jquery and wrap the code in: link
$( document ).ready(function() {
    console.log( "ready DOM" );
   // ваш код
});

The first thing to try is to transfer the connection of the js code below, but this is unlikely to help, you have to wait for the DOM to form
<canvas id="canvas"></canvas>

<script src="{% static 'js/main.js' %}"></script>
</body>
</html>

D
Dimonchik, 2020-03-09
@dimonchik2013

not enough code,
but if so, look at
1) logs
2) debugging
and instead of code, you can Hello Word and World! write

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question