6 Nisan 2022 Çarşamba

HTML Canvas Tag

Örnek
Şöyle yaparız
<canvas id="canvas" width="300" height="300"></canvas>
Kullanmak için şöyle yaparız
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');

// Create our image
let newImage = new Image();
newImage.src = 'https://fjolt.com/images/misc/202203281.png'

// When it loads
newImage.onload = () => {
    // Draw the image onto the context
    ctx.drawImage(newImage, 0, 0, 250, 208);
}
Açıklaması şöyle
When the image loads (newImage.onload), then we draw the image onto our canvas. To do that, we use ctx.drawImage(). The syntax is shown below.

ctx.drawImage(image, x, y, width, height)

If declared like this, ctx.drawImage() only has 5 arguments:
  • image - the image we want to use, is generated from our new Image() constructor.
  • x - the x position on the canvas for the top left corner of the image.
  • y - the y position on the canvas for the top left corner of the image.
  • width - the width of the image. If left blank, the original image width is used.
  • height - the height of the image. If left blank, the original image height is used.
toDataURL metodu
İmzası şöyle
toDataURL(type, encoderOptions) has two arguments which lets us change the way the canvas is encoded. This lets us save files as other formats, such as jpg.

Those two arguments can be defined as follows:
  • type, which is a filetype, in the format image/png.
  • encoderOptions, which is a number between 0 and 1, defining the image quality. This is only supported by file formats that have lossy compression, like webp or jpg.
Örnek
Şöyle yaparız
// Convert our canvas to a data URL
let canvasUrl = canvas.toDataURL("image/jpeg", 0.5);
console.log(canvasUrl);

// Outputs 
// "data:image/jpeg;base64,/9j/...
Örnek
Şöyle yaparız
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');

// Canvas code goes here 
// ...

document.getElementById('download').addEventListener('click', function(e) {
    // Convert our canvas to a data URL
    let canvasUrl = canvas.toDataURL();
    // Create an anchor, and set the href value to our data URL
    const createEl = document.createElement('a');
    createEl.href = canvasUrl;

    // This is the name of our downloaded file
    createEl.download = "download-this-canvas";

    // Click the download button, causing a download, and then remove it
    createEl.click();
    createEl.remove();
});

20 Mart 2022 Pazar

TypeScript Temel Tipler

Giriş
Açıklaması şöyle
... below is a list the most fundamental TypeScript types you will see the most:

undefined - when something is not defined in the code, or does not exist.
any - refers to any type - essentially not enforcing a type at all.
enum - an enum - see here for more on enums.
number - a number between -2^53 - 1 and 2^53 - 1, i.e. 1.
string - a combination of characters i.e. test.
boolean - true or false.
bigint - a number bigger than 253 - 1.
symbol - a completely unique identifier.
function - self-explanatory - a function.
object - an object or array
never - used in functions - for when a function never returns a value, and only throws an error.
void - used in functions - for when a function never returns a value.
Örnek
Şöyle yaparız
subject: string = "abc";

15 Aralık 2021 Çarşamba

DataTables

Giriş
Şu satırı dahil ederiz
<!-- DataTables.net -->
<script
src="resources/lib/dataTables-1.10.4/js/jquery.dataTables.min.js"
type="text/javascript"></script>
<script src="resources/lib/dataTables-1.10.4/js/dataTables.bootstrap.js"
type="text/javascript"></script>
<!-- TableTools - DataTables extension -->
<script
src="resources/lib/dataTables-1.10.4/extensions/TableTools-2.2.3/js/dataTables.tableTools.min.js"
type="text/javascript"></script>
Css için bir örnek burada

columns Alanı
Örnek
Şöyle yaparız
$('#weatherTable').DataTable({
  data: JSON.parse(res),
  columns: [
    { data: 'cityId' },
    { data: 'cityName' },
    { data: 'temp' },
    { data: 'tempMin' },
    { data: 'tempMax' },
    { data: 'pressure' },
    { data: 'humidity' }
  ],
  "pageLength": 5
});
ajaxSource Alanı
Örnek
index.hml şöyle olsun
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="utf-8" /> <title>...</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css"> <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script> <script src="/js/datatable.js"></script> </head> <body> <h1>Employees Table</h1> <table id="employeesTable" class="display"> <!-- Header Table --> <thead> <tr> <th>Id</th> <th>Name</th> <th>Last Name</th> <th>Email</th> <th>Phone</th> <th>Active</th> </tr> </thead> <!-- Footer Table --> <tfoot> <tr> <th>Id</th> <th>Name</th> <th>Last Name</th> <th>Email</th> <th>Phone</th> <th>Active</th> </tr> </tfoot> </table> </body> </html>
database.js şöyle olsun. Verinin alanları ve sütunlar eşleştirilir
$(document).ready( function () {
  var table = $('#employeesTable').DataTable({
    "sAjaxSource": "/employees",
    "sAjaxDataProp": "",
    "order": [[ 0, "asc" ]],
    "aoColumns": [
      { "mData": "id"},
      { "mData": "name" },
      { "mData": "lastName" },
      { "mData": "email" },
      { "mData": "phone" },
      { "mData": "active" }
    ]
  })
});
Şeklen şöyledir. "Show x entries" ve sayfalama otomatik eklenir. Ayrıca tüm veriyi çektiğim için sayfalamayı da DataTables kendisi yapar






14 Aralık 2021 Salı

Boostrap

Giriş
Twitter tarafından geliştirildi. İlk olarak 2011 yılında ortaya çıktı

fluid 12-grid system
Açıklaması şöyle
The Bootstrap grid system uses containers, rows, and columns to ensure that apps and websites are adaptable to devices of varied screen sizes, especially mobile screens. This 12-grid system follows a series of defined rules; for instance, rows are only used to create columns; rows must be empty; rows and columns come together to create containers, etc.

Örnek - bootstrap-3.3.1
Şu satırı dahil ederiz
<link href="resources/lib/bootstrap-3.3.1/css/bootstrap.min.css"
	rel="stylesheet">
...
<script src="resources/lib/bootstrap-3.3.1/js/bootstrap.min.js"
	type="text/javascript"></script>
Tables
Örnek - striped
Şöyle yaparız
"<table class='table table-striped'>


27 Eylül 2021 Pazartesi

HTML Header Tag

Örnek
Şöyle yaparız
<body>
  <header>
    <img src="/static/logo.png" alt="Logo">
    <nav>
      <a href="/">Main page</a>
    </nav>
  </header>
  <main>
    <article>
      <h1>Title</h1>
      <p>Content</p>
    </article>
  </main>
  <footer></footer>
</body>

7 Eylül 2021 Salı

HTML Embed Tag

Örnek - PDF
Şöyle yaparız
<embed id="plugin" type="application/x-google-chrome-pdf" src="..." 
...
>

2 Eylül 2021 Perşembe

TypeScript Type Guard

Giriş
Type Guard çeşitleri şöyle
null Guard
typeof Guard
instanceof Guard
in Guard
Discriminated Union Guards
User-Defined Guards
null Guard - null kontrolü yapar
Örnek
Şöyle yaparız
const element: HTMLElement | null = document.getElementById('target');

element.innerText = 'Hello'; // Compiler error - null in union

if (element !== null) {
    element.innerText = 'Hello'; // null removed from union 
}
null Guard yerine Optional kullanmak çok daha kolay. Şöyle yaparız.
element?.innerText = 'Hello';
typeof Guard
Örnek
Şöyle yaparız
// Note that the type of 'primitive' in each branch is different
switch (typeof primitive) { case "number": return primitive.toFixed(2); case "string": return primitive.toUpperCase(); case "boolean": return !primitive; default: throw new Error("Unexpected type") }
Açıklaması şöyle
Remember that typeof can only tell us if a type is string, number, boolean, symbol, function, bigint, undefined. Everything else will return "object".
instanceof Guard
Örnek
Şöyle yaparız
function setupInput(input: HTMLInputElement | HTMLTextAreaElement) {
    input.value = ''; // Valid since value is common to both types

    if (input instanceof HTMLTextAreaElement) {
        // These properties are only valid for HTMLTextAreaElement
        input.rows = 25;
        input.cols = 80;
        input.wrap = 'hard';
    } else {
        // These properties are only valid for HTMLInputElement
        input.width = 400;
        input.height = 50;
    }
}
in Guard
Örnek
Şöyle yaparız
function setupInput(input: HTMLInputElement | HTMLTextAreaElement) {
    if ('rows' in input) {
        // These properties are only valid for HTMLTextAreaElement
        input.rows = 25;
        input.cols = 80;
        input.wrap = 'hard';
    } else {
        // These properties are only valid for HTMLInputElement
        input.width = 400;
        input.height = 50;
    }
}
Açıklaması şöyle
The in operator allows us to test an object for the existence of a member. In the code below, only HTMLTextAreaElement has a rows property so by testing for its existence the compiler determines the type of the input variable on each branch and narrows the type.

Note, in can only be used if ALL members of the union are object types (not primitives).
in Guard kullanıyorsak return type'a dikkat etmek gerekir. Şöyle yaparız
function isTextArea(input: HTMLInputElement | HTMLTextAreaElement):
input is HTMLTextAreaElement { return 'rows' in input; } if (isTextArea(input)) { // input has type HTMLTextAreaElement input.rows = 25; // Valid }
Eğer şöyle yapsaydık derleme hatası alırdık. Çünkü boolean dönünce "type narrowing" yapılmıyor.
function isTextArea(input: HTMLInputElement | HTMLTextAreaElement): boolean {
    return 'rows' in input;
}

if (isTextArea(input)) {
    // input still has union type
    input.rows = 25; // Compiler error
}
Ayrıca TypeScipt 4.4 ile "type narrowing" şöyle de oluyor. Buna Control Flow Analysis information (CFA) deniliyor.
const isTextArea = 'rows' in input;

if (isTextArea) {
    // Narrowing has taken place
    input.rows = 25;
}
Örnek
Elimizde şöyle bir kod olsun.
interface A {
  text: string;
}
interface B {
  type: string;
}
type C = A|B;
B tipindeki nesneleri süzmek için şöyle yaparız.
function isB(c: C): c is B {
  if ('type' in c) { 
    return typeof c.type === 'string';
  }

  return false;
}
Elimizde bir array olsun.
const arr: Array<C> = [....]
Şöyle yaparız.
const output = arr.find(isB);