Вопрос по коду связанного с DOM
Вот эта кусок кода транслирует анимированный бекграунд сразу в body, а мне нужно что бы транслировал в нужный мне div подскажите пожалуйста где сменить и КАК сменить body на нужный мне div
// init var maxx = document.body.clientWidth; var maxy = document.body.clientHeight; var halfx = maxx / 2; var halfy = maxy / 2; var canvas = document.createElement("canvas"); document.body.appendChild(canvas); canvas.width = maxx; canvas.height = maxy; var context = canvas.getContext("2d"); var dotCount = 200; var dots = []; // create dots for (var i = 0; i < dotCount; i++) { dots.push(new dot()); } // dots animation function render() { context.fillStyle = "#000000"; context.fillRect(0, 0, maxx, maxy); for (var i = 0; i < dotCount; i++) { dots[i].draw(); dots[i].move(); } requestAnimationFrame(render); } // dots class // @constructor function dot() { this.rad_x = 2 * Math.random() * halfx + 1; this.rad_y = 1.2 * Math.random() * halfy + 1; this.alpha = Math.random() * 360 + 1; this.speed = Math.random() * 100 < 50 ? 1 : -1; this.speed *= 0.1; this.size = Math.random() * 5 + 1; this.color = Math.floor(Math.random() * 256); } // drawing dot dot.prototype.draw = function() { // calc polar coord to decart var dx = halfx + this.rad_x * Math.cos(this.alpha / 180 * Math.PI); var dy = halfy + this.rad_y * Math.sin(this.alpha / 180 * Math.PI); // set color context.fillStyle = "rgb(" + this.color + "," + this.color + "," + this.color + ")"; // draw dot context.fillRect(dx, dy, this.size, this.size); }; // calc new position in polar coord dot.prototype.move = function() { this.alpha += this.speed; // change color if (Math.random() * 100 < 50) { this.color += 1; } else { this.color -= 1; } }; // start animation render(); |
Цитата:
https://codepen.io/Malleys/pen/XQNpXK |
Пишет что
TypeError: Cannot read property 'clientWidth' of null для var myDiv |
Цитата:
if (Math.random() < .5) { |
Дело в том, что я запускаю эту функцию в компоненте react, а этот компонент вырисовывает блок в который должна идти анимация. Может мне как то запустить эту функцию после того, как компонент отрисовал нужный блок. Не очень понятно с импортом тут.
в bg-animation.js лежит вариант от Malleys import React, { Component } from 'react'; import './home.css'; import * as animation from './bg-animation.js'; export default class Home extends Component { componentDidMount() { console.log('DOM уже на странице') }; render() { return ( <div id="app"> </div> ) } }; |
Работает в таком виде только, если без импорта, спасибо
import React, { Component } from 'react'; import './home.css'; function DotAnimation(element) { var maxx = element.offsetWidth; var maxy = element.offsetHeight; var halfx = maxx / 2; var halfy = maxy / 2; var canvas = document.createElement("canvas"); element.appendChild(canvas); canvas.width = maxx; canvas.height = maxy; var context = canvas.getContext("2d"); var dotCount = 200; var dots = []; // create dots for (var i = 0; i < dotCount; i++) { dots.push(new Dot(halfx, halfy)); } // dots animation function render() { context.fillStyle = "#000000"; context.fillRect(0, 0, maxx, maxy); for (var i = 0; i < dotCount; i++) { dots[i].draw(context); dots[i].move(); } requestAnimationFrame(render); } render(); } // dots class // @constructor function Dot(halfx, halfy) { this.halfx = halfx; this.halfy = halfy; this.rad_x = 2 * Math.random() * this.halfx + 1; this.rad_y = 1.2 * Math.random() * this.halfy + 1; this.alpha = Math.random() * 360 + 1; this.speed = Math.random() * 100 < 50 ? 1 : -1; this.speed *= 0.1; this.size = Math.random() * 5 + 1; this.color = Math.floor(Math.random() * 256); } // drawing dot Dot.prototype = { draw: function(context) { // calc polar coord to decart var dx = this.halfx + this.rad_x * Math.cos(this.alpha / 180 * Math.PI); var dy = this.halfy + this.rad_y * Math.sin(this.alpha / 180 * Math.PI); // set color context.fillStyle = "rgb(" + this.color + "," + this.color + "," + this.color + ")"; // draw dot context.fillRect(dx, dy, this.size, this.size); }, // calc new position in polar coord move: function() { this.alpha += this.speed; // change color if (Math.random() * 100 < 50) { this.color += 1; } else { this.color -= 1; } } }; export default class Home extends Component { componentDidMount() { console.log('DOM уже на странице'); new DotAnimation(document.getElementById("app")); }; render() { return ( <div id="app"> </div> ) } }; |
Цитата:
https://codesandbox.io/s/m7o21ym6pj |
Цитата:
И есть ли на этом форуме ветка с React JS ? ^^ |
Цитата:
Цитата:
И затем вызов ReactDOM.findDOMNode(this.refs.canvasRoot); указывает на настоящий элемент, соответствующий React элементу. |
|
Часовой пояс GMT +3, время: 01:44. |