How to navigate a map to the region where user will press on map?
This blog is written for view a map and navigate it to a point by pressing here in react native.
To do it we need to change the map region by the value of latitude and longitude of the place where will be pressed on map.
Region is the middle point of map view.
Firstly we can set user location as initial region of the map to open it.
Then we have to set location point of the place where user pressed as the region of map view.
To find the latitude and longitude value of that palace we have to use onPress event of mapview. This event returns the location off that point where user pressed.
onPress is a Callback that is called when user taps on the map and return { coordinate: LatLng, position: Point }.
Using this onPress event we will animate map to that region using a function named animateMap().
In animateMap() function we need the reference of map view to animate it. So we make a reference here and the reference is _mapView.
The animateMap() function is given bellow-
After complete these the middle point of mapview will be moved on the place where user will press.
Thank You
Array, Tuple, Union in TypeScript
Array:
Array use of variables to store values. Array types can be written in one of two ways. In the first, you use the type of the elements followed by [] to denote an array of that element type.
Declaring and Initializing Arrays
To declare an initialize an array in Typescript uses the following syntax:
let arrayName:datatype[] //declaration
arrayName=[1,2,3] //initialization
many way array declaration
Tuple:
We know that an array holds multiple values of the same datatype. But sometimes, we may need to store a collection of values of different data types in a single variable. Arrays will not provide this feature, but TypeScript has datatype called tuple to achieve this purpose.
We may want to represent a value as a pair of a string and a number:
Declare a tuple type
Initialize it
Initialize it incorrectly
Accessing an element outside the set of known indices fails with an error:
Destructuring a Tuple
Union:
we can define a variable that can have multiple types of values. Two or more data types are combined using the pipe symbol (|) to denote a Union Type. In other words, a union type is written as a sequence of types separated by vertical bars.
Example: Union Type Variable
Reference: https://www.typescriptlang.org/docs/handbook/basic-types.html https://www.javatpoint.com/
Typescript
What is Typescript?
Typescript is a strongly typed, object oriented, compiled language. Typescript is both a language and a set of tools. Typescript is a typed superset of JavaScript compiled to JavaScript. In other words, Typescript is JavaScript plus some additional features.
Typescript
- Is purely object oriented programming.
- Can be used for client-side and server-side development alike
- Offers a “compiler” that can convert to JavaScript-equivalent code
- Has an API for DOM manipulation
- Has a namespace concept by defining a “Module”
Value Types:
Type define different types of value. The values can be different type. Typescript provides data types as a part of its optional Type System.
Mainly typescript can be two types. One is build I types and another is user defined types.
Build in types: build in types means that types are already given or declared in typescript.
Variables:
What is variable?
- A named space in the memory that stores values
- Variables are the container for values in a program
Naming Rules for variables:
- Variable names can contain alphabets and numeric digits.
- They cannot contain spaces and special characters, except the underscore (_) and the dollar ($) sign.
- Variable names cannot begin with a digit.
Declaration of variable:
Variable Scope:
- Global Scope− Global variables are declared outside the programming constructs. These variables can be accessed from anywhere within your code.
- Class Scope− These variables are also called fields. Fields or class variables are declared within the class but outside the methods. These variables can be accessed using the object of the class. Fields can also be static. Static fields can be accessed using the class name.
- Local Scope− Local variables, as the name suggests, are declared within the constructs like methods, loops etc. Local variables are accessible only within the construct where they are declared.
here, global_num is a global variable, class_num is class variable and local_num is a local variable.
Operators in Typescript:
An operator defines some function that will be performed on the data. The data on which operators work are called operands.
There are different types of variables in typescript. they are-
- Arithmetic operators
- Logical operators
- Relational operators
- Bitwise operators
- Assignment operators
- Ternary/conditional operator
- String operator
- Type Operator
Arithmetic operators:
Arithmetic operators are the symbols that represent arithmetic math operations.
Arithmetic operators are- Addition(+),subtraction(-), multiplication(*), Division(/), Modulus(%), increment(++), decrement(–).
Logical operators:
Logical operators are typically used with Boolean (logical) values. When they are, they return a Boolean value.
Relational operators:
Relational Operators test or define the kind of relationship between two entities. Relational operators return a Boolean value, i.e., true/ false.
Assignment operators:
Assignment operators are used to assign values to variables. This type of statement consists of a variable name, an assignment operator, and an expression.
Conditional operators:
This operator is used to represent a conditional expression. The conditional operator is also sometimes referred to as the ternary operator.
String operators:
- It is also called Concatenation operator (+).
- The + operator when applied to strings appends the second string to the first.
output will be: helloworld
Type Operators:
- It is a unary operator. This operator returns the data type of the operand.
output is: number
Decision making:
A decision-making construct evaluates a condition before the instructions are executed.
There are different types of conditional statement in typescript. They are…
- If statement.
- If else statement
- If else if statement
- Nested if statement
- Switch statement
If statement:
The if statement evaluates a condition and, if the condition’s result is true then execute a block of code that are inside the if statement.
example:
If else:
It also check the condition and when the condition is true , if statement will be executed otherwise else statement will be executed.
example:
If else if statement:
It can check more than one condition if first condition is true then execute first statement otherwise check another condition in else if then if true then execute else if statement if it is also false then execute else statement.
Nested if condition:
It will check the if condition then another condition will be given inside the if statement. Flowchart is given bellow-
Example:
output:
Switch statement:
The switch case statement is used when we have multiple options and we need to perform a different task for each option.
example:
output:
Loops in Typescript:
A loop statement allows us to execute a statement or group of statements multiple times. Given below is the general form of a loop statement in most of the programming languages.
Types of loops:
There are different loops in typescript. They are given bellow-
Definite loop:
- A loop whose number of iterations are definite/fixed is termed as a definite loop. The for loopis an implementation of a definite loop.
for loop:
The for loop is an implementation of a definite loop. it given a fixed number for continue.
Different for loops:
- for loop
- for..of loop
- for..in loop
example:
While loop:
The while loop is another type of loop that checks for a specified condition before beginning to execute the block of statements. The loop runs until the condition value is met.
syntax: while(condition){statement}
example:
output:
Do while loop:
The do..while loop is similar to the while loop, except that the condition is given at the end of the loop. The do..while loop runs the block of code at least once before checking for the specified condition.
syntax: do{statement}while(condition)
example:
output:
Function:
Functions are the building blocks of readable, maintainable, and reusable code. A function is a set of statements to perform a specific task. Functions organize the program into logical blocks of code.
Defining a Function:
A function definition specifies what and how a specific task would be done. Before using a function, it must be defined. Functions are defined using the function keyword.
syntax:
function function_name() { // function body }
Calling a function:
A function must be called so as to execute it. This process is termed as function invocation.
syntax: function_name();
Parameters in function:
Optional parameters can be used when arguments need not be compulsorily passed for a function’s execution. A parameter can be marked optional by appending a question mark to its name. The optional parameter should be set as the last argument in a function.
syntax:
function function_name (param1[:type], param2[:type], param3[:type])
Rest Parameters:
Rest parameters don’t restrict the number of values that you can pass to a function. In other words, rest parameters act as placeholders for multiple arguments of the same type. To declare a rest parameter, the parameter name is prefixed with three periods.
example:
Default parameter:
Function parameters can also be assigned values by default. However, such parameters can also be explicitly passed values.
syntax:
function function_name(param1[:type],param2[:type] = default_value) { }
Note − A parameter cannot be declared optional and default at the same time.
example:
Anonymous function:
Functions that are not bound to an identifier (function name) are called as anonymous functions. These functions are dynamically declared at runtime.An anonymous function is usually not accessible after its initial creation.
syntax:
var res = function( [arguments] ) { … }
example:
Recursion:
Recursion is best applied when you need to call the same function repeatedly with different parameters from within a loop.
example:
Lambda function:
Lambda refers to anonymous functions in programming. Lambda functions are a concise mechanism to represent anonymous functions. These functions are also called as Arrow functions.
Example:
reference: https://www.tutorialspoint.com/typescript
Namespaces:
The namespace is used for logical grouping of functionalities. A namespace can include interfaces, classes, functions and variables to support a single or a group of related functionalities.
A namespace can be created using the namespace keyword followed by the namespace name. All the interfaces, classes etc. can be defined in the curly brackets { }.
Syntax:
How can we use namespace?
In this example, we have a namespace named studentcal in file studentcalc.ts. We want to use the feeCalc function in another program. That’s why export keyword should use before the desire function.
Now we want to use the studentcal namespace as well as feeCalc function to calculate a value in a new program app.ts using the reference just like below code.
If we run this app.ts using the following command we will get an error indicates “can’t find studentcal”.
To solve this problem, we have to combine this two files studentcalc.ts and app.ts. A file named out.js. will be created if we command this line-
We got a new file named out.js. Then we have to run this out.js and that will solve the problem.
Happy Coding!!!!!
File System Module:
The Node.js file system module allows you to work with the file system on your computer. It exports functions for working with files and directories. The fs module is responsible for all the asynchronous or synchronous file I/O operations.
To include the File System module, use the require() method:
we can perform read, write, delete and many more operations. Let us look at some of the most important operations.
Reading Files Synchronously and Asynchronously
The fs module provides simple methods to read files: fs.readFile() and fs.readFileSync(). The fs.readFile() is for reading file asynchronously and fs.readFileSync() is for reading files synchronously.
Here, file path has to be provided as a first argument and a callback function that will be called with file data.
For fs.readFileSync(), file path has to be provided as a first argument. utf8 is the default encoding, but we can specify any custom encoding that we need as the second parameter in both the methods.
Writing Files Synchronously and Asynchronously
Create a new file using the fs.writeFile() and fs.writeFileSync() method. The fs.writeFile() is for reading file asynchronously and fs.writeFileSync() is for reading files synchronously.
In the synchronous write operation
Deleting a File
To delete a file with the File System module, use the fs.unlink() method.
Renaming a File
A file can be renamed using fs.rename(). Here, it takes old file name, new file name and a callback function as arguments.
Streams in Node.js
What is stream?
Streams are the collection of data like array or strings but the difference is that the all streams might not be available at a once and they don’t have to fit in memory. Stream is very useful to work with large amount of data and the data’s that’s come from the external source. They also give us power of composability in code.
Streams are also objects that we read data from a source or write data to a destination in continuous fashion.
Why Stream?
The advantage of stream is given bellow-
- Memory efficiency: No need to carry the massive amounts of data in memory before process it.
- Time efficiency: It takes way less time to start processing the data as soon as you have it, rather than waiting till the whole data payload is available to start the process.
Types of streams:
There are four types of streams. They are-
- Writable streams
- Readable streams
- Duplex
- Transform
We are going to describe about writable stream and readable stream.
Writable streams: Writable streams are the streams which data can be written. Writable object has a write() method which pass string or buffer to write something to the stream. And also a end() method that close the stream and give value in time of closing.
We can create a writable stream using createWriteStream() method. The example is given bellow-
Readable Stream: Readable stream is read data from source. The source can be simple file in file system, a buffer in memory, or even another stream.
creteReadStream() method is used to create a file readable from fs. Example is given bellow-
We can also read file using readFile() method.
Difference between writable Stream and Readable stream-
Screenshot captured from my Pluralsight course — Advanced Node.js
We know web technology works on the server site and client site. We will not go deep through this fact but we will just see how this simply works with http module in node.js.
In this article, we will know What is HTTP Module?, How can HTTP module be used to create server?. Then let’s start—-
Http Module:
Node.js has a built-in module called HTTP, which allows Node.js to transfer data over the Hyper Text Transfer Protocol (HTTP).
To include the HTTP module, use the require() method:
How can we use node.js as a web server using Http Module:
We can use createServer() method to create the server.
In above code, we imported {createServer} module using require directive to access HTTP module. The function passed into the http.createServer() method, will be executed when someone tries to access the computer on port 8000. The request and response bindings are objects representing the incoming and outgoing data. The first contains information about the request, such as its url property which tells us to what URL the request was made.
So, when one open that page in the browser, it sends a request to his/her own computer. This the causes the created server (In this case, server) to run and send back a response, which can be seen in the browser.
To send something back, response object works. writeHead() method set the server response type. Here, the content will be shown as html page. Multiple header may be use. The actual response method is sent with write() method. The call to server.listen() causes the server to start waiting for connections on port 8000. Finally, the response ends with response.end() method. If we initiate our code as –
We will see this in the browser as expected.
That’s for today. Happy Coding!!!!!
Reference-https://eloquentjavascript.net/20_node.html
CSS is a complex language that packs quite a bit of power. We know that CSS, or Cascading Styles Sheets, is a way to style and present HTML. Whereas the HTML is the meaning or content, the style sheet is the presentation of that document.
All styles cascade from the top of a style sheet to the bottom, allowing different styles to be added or overwritten as the style sheet progresses. We already know that CSS is a vast thing, so, I’ll discuss some important rules. Such as,
- Class and Id selectors
- Grouping and Nesting
- Pseudo Classes
- Shorthand Properties
- Background Images
- Page Layout
Class and Id selectors
In the CSS, a class selector is a name preceded by a full stop (“.”) and an ID selector is a name preceded by a hash character (“#”).
The difference between an ID and a class is that an ID can be used to identify one element, whereas a class can be used to identify more than one.
Grouping and Nesting
You can give the same properties to a number of selectors without having to repeat them.
You can simply separate selectors with commas in one line and apply the same properties.
Nesting
If the CSS is structured well, there shouldn’t be a need to use many class or ID selectors. This is because you can specify properties to selectors within other selectors.
Shorthand Properties
Some CSS properties allow a string of values, replacing the need for a number of properties. These are represented by values separated by spaces.
Margins and Padding
Margin allows you to amalgamate margin-top, margin-right, margin-bottom,
and margin-left in the form of property: top right bottom left;
Borders
Border-width can be used in the same way as margin and padding, too. You can also combine border-width, border-color, and border-style with the border property.
Background image
CSS background images are a powerful way to add detailed presentation to a page.
Page Layout
Layout with CSS is easy. You just take a chunk of your page and shove it wherever you choose. You can place these chunks absolutely or relative to another chunk.
The position property is used to define whether a box is absolute, relative, static or fixed
Floating a box will shift it to the right or left of a line, with surrounding content flowing around it.
Floating is normally used to shift around smaller chunks within a page, such as pushing a navigation link to the right of a container, but it can also be used with bigger chunks, such as navigation columns. Using float, you can float: left or float: right.
Positioning
The position property is used to define whether a box is absolute, relative, static or fixed:
- static is the default value and renders a box in the normal order of things, as they appear in the HTML.
- relative is much like static but the box can be offset from its original position with the properties top, right, bottom and left.
- absolute pulls a box out of the normal flow of the HTML and delivers it to a world all of its own. In this crazy little world, the absolute box can be placed anywhere on the page using top, right, bottom and left.
- fixed behaves like absolute, but it will absolutely position a box in reference to the browser window as opposed to the web page, so fixed boxes should stay exactly where they are on the screen even when the page is scrolled.
How a box’s position is calculated
A box can be positioned with the top, right, bottom, and left properties. These will have different effects depending on the value of position.
relative: Position is offset from the initial position.
absolute: Taken out of the flow and positioned in relation to the containing box.
fixed: Taken out of the flow and positioned in relation to the viewport. It will not scroll with the rest of the page’s content.
Floating
Floating a box will shift it to the right or left of a line, with surrounding content flowing around it.
Floating is normally used to shift around smaller chunks within a page, such as pushing a navigation link to the right of a container, but it can also be used with bigger chunks, such as navigation columns.
Using float, we can use float: left or float: right
Example:
Rounded Corners
Rounded corners used to be the stuff of constricting solid background images or, for flexible boxes, numerous background images, one per-corner, slapped on multiple nested div elements.
Border radius?
Border radius. Fear not, though — don’t have to have borders. The border-radius property can be used to add a corner to each corner of a box.
Before After
Example: different type of borders –radius measurements
Box Shadows
- The first value is the horizontal offset — how far the shadow is nudged to the right (or left if it’s negative)
- The second value is the vertical offset — how far the shadow is nudged downwards (or upwards if it’s negative)
- The third value is the blur radius — the higher the value the less sharp the shadow. (“0” being absolutely sharp). This is optional — omitting it is equivalent of setting “0”.
- The fourth value is the spread distance — the higher the value, the larger the shadow (“0” being the inherited size of the box). This is also optional — omitting it is equivalent of setting “0”.
- The fifth value is a color. That’s optional, too.
Targeting media types
@media can be used to apply styles to a specific media, such as print.
Embedding fonts
It is now widely used as a technique for embedding fonts in a web page
Reference
HTML Basics
HTML (Hypertext Markup Language) is the most basic building block of the Web. It defines the meaning and structure of web content.HTML are generally used to describe a web page’s appearance/presentation (CSS) or functionality/behavior (JavaScript).
“Hypertext” refers to links that connect web pages to one another, either within a single website or between websites. Links are a fundamental aspect of the Web.
A Simple HTML Document
HTML uses “markup” to annotate text, images, and other content for display in a Web browser. HTML markup includes special “elements” such as <head>, <title>, <body>, <header>, <footer>, <article>, <section>, <p>, <div>, <span>, <img>, <aside>, <audio>, <canvas>, <datalist>, <details>, <embed>, <nav>, <output>, <progress>,
<video> and many others.
HTML Elements
An HTML element usually consists of a start tag and an end tag, with the content inserted in between
- The opening tag:This consists of the name of the element (in this case, p), wrapped in opening and closing angle brackets. This states where the element begins or starts to take effect — in this case where the paragraph begins.
- The closing tag:This is the same as the opening tag, except that it includes a forward slash before the element name. This states where the element ends — in this case where the paragraph ends. Failing to add a closing tag is one of the standard beginner errors and can lead to strange results.
- The content:This is the content of the element, which in this case, is just text.
- The element:The opening tag, the closing tag and the content together comprise the element.
HTML Attributes
Attributes provide additional information about HTML elements.
Attributes contain extra information about the element that you don’t want to appear in the actual content. Here, class is the attribute name and editor-note is the attribute value. The class attribute allows you to give the element an identifier that can be used later to target the element with style information and other things.
Nested HTML Elements
HTML elements can be nested (elements can contain elements).
All HTML documents consist of nested HTML elements.
This example contains four HTML elements:
In the example above, we opened the <p> element first, then the <strong> element; therefore, we have to close the <strong> element first, then the <p> element.
HTML Empty Elements
HTML elements with no content are called empty elements.
<br> is an empty element without a closing tag (the <br> tag defines a line break):
This contains two attributes, but there is no closing </img> tag and no inner content. This is because an image element doesn’t wrap content to affect it. Its purpose is to embed an image in the HTML page in the place it appears.
Anatomy of an HTML Document
- <!DOCTYPE html>— the doctype. It is required preamble. In the mists of time, when HTML was young (around 1991/92), doctypes were meant to act as links to a set of rules that the HTML page had to follow to be considered good HTML, which could mean automatic error checking and other useful things. However these days, they don’t do much, and are basically just needed to make sure your document behaves correctly. That’s all you need to know for now.
- <html></html>— the <html> This element wraps all the content on the entire page and is sometimes known as the root element.
- <head></head>— the <head> This element acts as a container for all the stuff you want to include on the HTML page that isn’t the content you are showing to your page’s viewers. This includes things like keywords and a page description that you want to appear in search results, CSS to style our content, character set declarations and more.
- <meta charset=”utf-8″>— This element sets the character set your document should use to UTF-8 which includes most characters from the vast majority of written languages. Essentially, it can now handle any textual content you might put on it. There is no reason not to set this and it can help avoid some problems later on.
- <title></title>— the <title> This sets the title of your page, which is the title that appears in the browser tab the page is loaded in. It is also used to describe the page when you bookmark/favourite it.
- <body></body>— the <body> This contains all the content that you want to show to web users when they visit your page, whether that’s text, images, videos, games, playable audio tracks or whatever else.
Lists
Marking up lists always consist of at least 2 elements. Lists are two types
- Ordered list
- Unordered list
Ordered List
Ordered list are for lists where the order of the items does matter, such as a recipe. These are wrapped in an <ol> element.
Unordered List
Unordered lists are for lists where the order of the items doesn’t matter, such as a shopping list. These are wrapped in a <ul> element.
Links
Links are very important — they are what makes the web a web!
HTML links are hyperlinks.
You can click on a link and jump to another document.
When you move the mouse over a link, the mouse arrow will turn into a little hand.
To add a link, we need to use a simple element — <a> — “a” being the short form for “anchor”.
We also fill in the value of this attribute with the web address that you want the link to link to:
Reference Links:
- https://developer.mozilla.org/en-US/docs/Web/HTML
- https://www.w3schools.com/html/default.asp
- https://en.wikipedia.org/wiki/HTML
CSS Basics
Cascading Stylesheets — or CSS is used to style it and lay it out. For example, you can use CSS to alter the font, color, size, and spacing of your content, split it into multiple columns, or add animations and other decorative features.
Web browsers apply CSS rules to a document to affect how they are displayed. A CSS rule is formed from:
- A set of properties, which have values set to update how the HTML content is displayed.
- A selector, which selectsthe element(s) we want to apply the updated property values to.
At its most basic level, CSS consists of two building blocks:
- Properties: Human-readable identifiers that indicate which stylistic features (e.g., font, width, background color) you want to change.
- Values: Each specified property is given a value, which indicates how you want to change those stylistic features (e.g., what you want to change the font, width, or background color to.)
CSS is case-sensitive so be careful with your capitalization. CSS has been adopted by all major browsers and allows you to control:
- color
- fonts
- positioning
- spacing
- sizing
- decorations
- transitions
How to Use CSS?
There are three main ways to apply CSS styling. You can apply inline styles directly to HTML elements with the style-attribute. Alternatively, you can place CSS rules within style-tags in an HTML document. Finally, you can write CSS rules in an external style sheet, then reference that file in the HTML document. Even though the first two options have their use cases, most developers prefer external style sheets because they keep the styles separate from the HTML elements. This improves the readability and reusability of your code. The idea behind CSS is that you can use a selector to target an HTML element in the DOM (Document Object Model) and then apply a variety of attributes to that element to change the way it is displayed on the page.
External Style Sheet
With an external style sheet, we can change the look of an entire website by changing just one file!
Each page must include a reference to the external style sheet file inside the <link> element. The <link> element goes inside the <head> section:
Example:
Inline style sheet
An inline style may be used to apply a unique style for a single element.
Example:
Internal style sheet
An internal style sheet may be used if one single page has a unique style.
Example:
CSS Selector
In CSS, selectors are used to target the HTML elements on our web pages that we want to style
There are three types of selectors:
- ID Selectors
- Class Selectors
- Groping Selectors
ID Selectors
- The id selector uses the id attribute of an HTML element to select a specific element.
- The id of an element should be unique within a page, so the id selector is used to select one unique element!
Class Selectors
- The class selector selects elements with a specific class attribute.
To select elements with a specific class, write a period (.) character, followed by the name of the class.
Grouping Selectors
If we have elements with the same style definitions, like this:
It will be better to group the selectors, to minimize the code.
To group selectors, separate each selector with a comma.
Reference
- https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/Selectors
- https://learn.freecodecamp.org/responsive-web-design/basic-css/
- https://www.w3schools.com/css/default.asp
This blog is a pixel art editor implements. please read the previous blog.
link: 1. http://enlightsolution.com/javascript/a-pixel-art-editor-how-to-create-a-canvas-draw-on-it/
2. http://enlightsolution.com/javascript/drawing-tools-in-a-pixel-art-editor/
When we’ve drawn our masterpiece, we’ll want to save it for later. So that we use this picture. We should add a button for downloading the current picture as an image file.
How to work save button?
The first step create the save button by elt() function. The elt() function get type, properties and child than finally return the DOM structure. Details elt() function please visit a previous blog, link: http://enlightsolution.com/javascript/a-pixel-art-editor-how-to-create-a-canvas-draw-on-it/
save() function call when the click save button. The component keeps track of the current picture so that it can access it when saving. The current picture get by state.picture. To create the image file, it uses a <canvas> element that it draws the picture on (at a scale of one pixel per pixel) by drawPicture() function. If you details, how to work drawPicture() function, visit previous blog, link: http://enlightsolution.com/javascript/a-pixel-art-editor-how-to-create-a-canvas-draw-on-it/
Again elt() function create another(<a>) tag. Here another tag attributes is href and download. The toDataURL method on a canvas element creates a URL. They are usually very long, but they allow us to create working links to arbitrary pictures, right here in the browser.
To actually get the browser to download the picture, we then create a link element that points at this URL and has a download attribute. The download attribute specifies that the target will be downloaded when a user clicks on the hyperlink(href). Such links, when clicked, make the browser show a file save dialog. We add that link to the document by document.boby.appendchild(), simulate a click on it, and remove it again.
How to work load-Button?
We’ll also want to be able to load existing image files into our application and edit this image. To do that, we again define a button component.
The load button create by elt() function, similarly to save button.
startLoad() function call when the click load button. To get access to a file on the user’s computer, we need the user to select the file through a file input field. But I don’t want the load button to look like a file input field, so we create the file input when the button is clicked and then pretend that this file input itself was clicked.
Finishload() call when input field change, here change means this input remove.
If a user no file selected, no execute other code. When the user has selected a file, we can use FileReader to get access to its contents, again as a data URL. That URL can be used to create an <img> element by elt() function, but because we can’t get direct access to the pixels in such an image, we can’t create a Picture object from that. The image path get by reader.result.
We already get the image. We’ll limit the size of images to 100 by 100 pixels since anything bigger will look huge on our display and might slow down the interface. Canvas tag again create by elt() function. The canvas element has a DOM method called getContext, used to obtain the rendering context and its drawing functions. This function takes one parameter, the type of context 2d.So getcontext method returns a drawing context on the canvas.
we use for drawing an image onto a canvas is the drawImage() function. context.drawImage(img,x,y), here img means specifies the image, x coordinate where to place the image on the canvas and y coordinate where to place the image on the canvas. Finally, draw in canvas. But, we do not have any color information. For that finish the work.
The data property of the object returned by getImageData is an array of color components. For every pixel in a getmageData object there are four pieces of information, which represent the red, green, blue, and alpha components of the pixel’s color. We need red, green, blue values, but not need alpha value. So we use the slice() function.
The hex() function return the hexadecimal digits. We have to make sure that each number takes up two digits, so the hex helper function calls padStart to add a leading zero when necessary. Finally, return the picture object.