add json func

This commit is contained in:
2022-04-03 09:04:24 +03:00
parent 909cd73762
commit a42013753a
39 changed files with 83 additions and 0 deletions

21
~/JavaScript/README.md Normal file
View File

@ -0,0 +1,21 @@
# JavaScript
## Basic
- [Arrays](arrays.js) - работа с массивами
- [Spread syntax](spread.js) - распаковка массива в аргументы
- [fetch](fetch.js) - ...
- [location.href](location.href.js) - Переход на другую страницу
- [Text Content](textContent.js) - Получить текстовое содержимое элемента
- [Add DOM Elements](addElements.js) - Добавление элементов в DOM
- [Add Class](addClass.js) - Добавление/Удаление классов
## Other
- [Webpack](webpack.md) example config
## Canvas
- [Drawing text](drawing-text.js) - примеры рисования текста на CANVAS
- [`measureText()`](measureText.js) - возвращает информацию об измеренном тексте, например ширину
- [`drawImage()`](canvas.drawImage.js) - метод Canvas 2D API рисования изображения на холсте
## GameDev
- Canvas [GameLoop](gameloop.js) example

5
~/JavaScript/addClass.js Normal file
View File

@ -0,0 +1,5 @@
// Use element.classList.add to add a class:
element.classList.add('my-class');
// And element.classList.remove to remove a class:
element.classList.remove('my-class');

View File

@ -0,0 +1,3 @@
let newDiv = document.createElement('div');
newDiv.appendChild(document.createTextNode('some text'));
document.body.appendChild(newDiv);

17
~/JavaScript/arrays.js Normal file
View File

@ -0,0 +1,17 @@
let cats = ['Bob', 'Willy', 'Mini'];
// pop(): Remove an item from the end of an array
// pop() returns the removed item
cats.pop(); // ['Bob', 'Willy']
// push(): Add items to the end of an array
// push() returns the new array length
cats.push('Mini'); // ['Bob', 'Willy', 'Mini']
// shift(): Remove an item from the beginning of an array
// shift() returns the removed item
cats.shift(); // ['Willy', 'Mini']
// unshift(): Add items to the beginning of an array
// unshift() returns the new array length.
cats.unshift('Puff', 'George'); // ['Puff', 'George', 'Willy', 'Mini']

View File

@ -0,0 +1,44 @@
// void ctx.drawImage(image, dx, dy);
// void ctx.drawImage(image, dx, dy, dWidth, dHeight);
// void ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
// image
// Элемент для отображения в контексте.
// Функция принимает любой источник изображения, пригодный для отображения
// на холсте
// dx
// Координата по оси Х, обозначающая стартовую точку холста-приёмника,
// в которую будет помещён верхний левый угол исходного image.
// dy
// Координата по оси Y, обозначающая стартовую точку холста-приёмника,
// в которую будет помещён верхний левый угол исходного image.
// dWidth
// Ширина изображения, полученного из исходного image.
// Эта опция позволяет масштабировать изображение по ширине.
// Если опция не задана, изображение не будет масштабировано.
// dHeight
// Высота изображения, полученного из исходного image.
// Эта опция позволяет масштабировать изображение по высоте.
// Если опция не задана, изображение не будет масштабировано.
// sx
// Координата по оси X верхнего левого угла фрагмента,
// который будет вырезан из изображения-источника и помещён в контекст-приёмник.
// sy
// Координата по оси Y верхнего левого угла фрагмента,
// который будет вырезан из изображения-источника и помещён в контекст-приёмник.
// sWidth
// Ширина фрагмента, который будет вырезан из изображения источника
// и помещён в контекст-приёмник. Если не задана, фрагмент от точки,
// заданной sx и sy до правого нижнего угла источника
// будет целиком скопирован в контекст-приёмник.
// sHeight
// Высота фрагмента, который будет вырезан из изображения источника
// и помещён в контекст-приёмник.
function Draw() {
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
let image = document.getElementById('source');
ctx.drawImage(image, 33, 71, 104, 124, 21, 20, 87, 104);
}

View File

@ -0,0 +1,14 @@
function Draw() {
let context = document.getElementById('canvas').getContext('2d');
// Styling text
// font = value
// textAlign = value | *start, end, left, right, center
// textBaseline = value | top, hanging, middle, *alphabetic, ideographic, bottom
// direction = value | ltr, rtl, *inherit
// fillText(text, x, y [, maxWidth])
// strokeText(text, x, y [, maxWidth])
context.font = '48px serif';
context.fillText('Hello world', 10, 50);
}

3
~/JavaScript/fetch.js Normal file
View File

@ -0,0 +1,3 @@
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));

113
~/JavaScript/gameloop.js Normal file
View File

@ -0,0 +1,113 @@
// Main variables
let DEBUG = true;
let canvas;
let context;
let cW;
let cH;
// FPS
let secondsPassed;
let oldTimeStamp;
let fps;
let dragging = false;
function mMove(e) {
'use strict';
if (dragging) {
point.pX = e.offsetX * cW / canvas.clientWidth | 0;
point.pY = e.offsetY * cH / canvas.clientHeight | 0;
};
}
function mDown(e) {
'use strict';
dragging = true;
}
function mUp(e) {
'use strict';
dragging = false;
}
function clearContext() {
'use strict';
context.fillStyle = '#b27e56';
context.fillRect(0, 0, cW, cH);
}
// Init
window.onload = function() {
'use strict';
canvas = document.getElementById('game');
context = canvas.getContext('2d');
cW = canvas.width;
cH = canvas.height;
canvas.style.height = window.innerHeight + "px";
if (DEBUG) {
console.log('Canvas set size to ' + window.innerHeight + 'px');
console.log(canvas.getBoundingClientRect());
};
canvas.addEventListener('mousedown', mDown, false);
canvas.addEventListener('mouseup', mUp, false);
canvas.addEventListener('mousemove', mMove, false);
canvas.addEventListener('touchstart', mDown, false);
canvas.addEventListener('touchend', mUp, false);
canvas.addEventListener('touchmove', mMove, false);
window.requestAnimationFrame(gameLoop);
};
window.addEventListener('resize', function() {
'use strict';
let canvas = document.getElementById('game');
canvas.style.height = window.innerHeight + "px";
if (DEBUG) {
console.log('Canvas resized to ' + window.innerHeight + 'px');
console.log(canvas.getBoundingClientRect());
};
}, true);
// GameLoop
function gameLoop(timeStamp) {
'use strict';
// fps counter
secondsPassed = (timeStamp - oldTimeStamp) / 1000;
oldTimeStamp = timeStamp;
fps = Math.round(1 / secondsPassed);
// end fps counter
update();
draw();
if (DEBUG) {
context.font = '15px Arial';
context.fillStyle = '#101024';
context.fillText('FPS: ' + fps, 10, 20);
};
window.requestAnimationFrame(gameLoop);
}
function update() {
'use strict';
//
}
function draw() {
'use strict';
clearContext();
}

View File

@ -0,0 +1,4 @@
// Перейти на нужную страницу можно с помощью JavaScript
// document.location.href = "https://www.site";
document.location.href = url.value;

View File

@ -0,0 +1,5 @@
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let text = ctx.measureText('Hello world');
console.log(text.width); // 56;

11
~/JavaScript/spread.js Normal file
View File

@ -0,0 +1,11 @@
function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers));
// expected output: 6
console.log(sum.apply(null, numbers));
// expected output: 6

View File

@ -0,0 +1,3 @@
document.getElementById('element').textContent;
// If you need to target < IE9 then you need to use
document.getElementById('element').innerText;

33
~/JavaScript/webpack.md Normal file
View File

@ -0,0 +1,33 @@
## WebPack
`packages.json`
```json
"scripts": {
"serve": "webpack serve",
"html": "html-minifier --collapse-whitespace --remove-comments src/index.html --output dist/index.html",
"css": "csso src/styles.css --output dist/styles.css",
"build": "npm run html && npm run css && webpack --mode=production"
},
"devDependencies": {
"webpack": "^5.42.0",
"webpack-cli": "^4.7.2",
"webpack-dev-server": "^3.11.2"
}
```
`webpack.config.js`
```javascript
const path = require('path');
module.exports = {
mode: 'development',
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'engine.js',
},
devServer: {
contentBase: path.join(__dirname, 'src'),
compress: false,
port: 55555,
},
};
```