Total Pageviews

Sunday 14 June 2015

JavaScript : Drag And Drop

Drag and Drop is a very common feature and it is mostly used in games and wherever needed.

<html>
 <head> <title> Drag And Drop </title> </head>
 <body>
        <style>
            #dropDiv {width:350px;height:70px;padding:10px;border:1px solid #aaaaaa;}
        </style>


        <script>
                function drag(ev)
                {
                    ev.dataTransfer.setData("text", ev.target.id);
                }
               
                function drop(ev)
                {
                    ev.preventDefault();
                    var data = ev.dataTransfer.getData("text");
                    ev.target.appendChild(document.getElementById(data));
                }
               
                function allowDrop(ev)
                {
                    ev.preventDefault();
                }
        </script>
       
       

        <div id="dropDiv" bgcolor="0x000000" ondrop="drop(event)"  
         ondragover="allowDrop(event)"> </div>

        <img src="logo.jpg" id="image1" draggable="true" width="336" height="69"    ondragstart="drag(event)"> 

 </body>
</html>


Not a very complex thing to understand, there are few methods which we need to understand :

Set the object draggable property true.
draggable="true"

 dataTransfer.setData() sets the datatype of an object and value of an object.

preventDefault() to prevent the browser default handling of the data (default is open as link on drop).

Append the dragged element into the drop element.

AS3 :: Paste the Copied Text into a TextField on Stage


Since Flash Player 10, flash embedded on websites apps are just able to access to the Clipboard.generalClipboard.getData() method just when they are processing a PASTE event dispatched directly by the user.

Below is the example : 

package
{
    import flash.display.Sprite;
    import flash.desktop.Clipboard;
    import flash.desktop.ClipboardFormats;
    import flash.desktop.ClipboardTransferMode;
    import flash.events.*;
    import flash.system.System;

    public class ClipboardExample extends Sprite
    {
       public function ClipboardExample()
       {  
           Clipboard.generalClipboard.clear();
           copyButton.addEventListener(MouseEvent.MOUSE_UP, copyText);
       }

       private function copyText(e:MouseEvent):void
       {
           Clipboard.generalClipboard.clear();
           System.setClipboard(myField.text);
           messageField.text = "Copied!";
           stage.addEventListener(Event.PASTE,paste); //Ctrl+V on stage
       }    

       private function paste(e:Event):void
       {
          if(Clipboard.generalClipboard.hasFormat(ClipboardFormats.TEXT_FORMAT))
          {              
             messageField.text =String(Clipboard.generalClipboard.getData(ClipboardFormats.TEXT_FORMAT));
          }
      }
   }  
 }

Saturday 13 June 2015

AS3 :: To Load and display data into ComboBox from external XML using MVC Design Pattern.


MVC  :  is a design pattern used to isolate business logic from user interface. This increase the modification of UI and Logic easily without affecting other areas of application.

MVC stands for Model , View Controller.

Model : Stores the data throughout the application.

View : Represents the display and Communication part of an application. One view can have multiple models.

Controller : All the logic part handling.

Below is the small and simple example :

First, Create a Fla and drag a combox component from User Interface option in Components Group.












Second, we need a xml from which we load data. So i have created a small one and named the file books.xml

<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="web" cover="paperback">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>

</bookstore>


we need to create a view to display combo box and model and controller respectively.

DropDownView.as

package view
{
import flash.display.MovieClip;
import model.DropDownModel;
import controller.DropDownController;
import flash.events.Event;

import fl.events.ComponentEvent;
import fl.controls.ComboBox;
import fl.data.DataProvider;

public class DropDownView extends MovieClip
{
private var _model:DropDownModel;
private var _controller:DropDownController;
private var aCb:ComboBox;

public function DropDownView(m:DropDownModel,c:DropDownController)
{
_model = m;
_controller = c;

_model.addEventListener(DropDownModel.UPDATE, update);

aCb = new ComboBox();
addChild(aCb);
aCb.x = 200;
aCb.y = 100;
aCb.dropdownWidth = 296;
aCb.width = 300;
aCb.prompt = "Select Author :";
}

private function update(e:Event):void
{
trace(_model.itemText.length);

for(var i:uint=0;i<_model.itemText.length;i++)
           {
aCb.addItem( { label: _model.itemText[i], data:i } );
aCb.addEventListener(Event.CHANGE, changeHandler);
}
}

private function changeHandler (e : Event ) : void
{
var getSelectedData:Number = Number(aCb.selectedItem.data);
           trace(_model.itemText[getSelectedData]);
                       // do further work
}
}
}

Every view must have an update function to update the view with latest data set after actions.

Below is the model class to store data :

DropDownModel.as

package  model
{
import flash.events.EventDispatcher;
import flash.events.Event;
public class DropDownModel extends EventDispatcher
{
public static var UPDATE:String='ModelUpdated';
private var _text:Array=[];
public function DropDownModel() 
{
}
public function get itemText():Array
{
return _text;
}
public function set itemText(s:Array):void
{
_text=s;
dispatchEvent(new Event(DropDownModel.UPDATE));
}
}
}

To Load the external xml we create a controller class name DropDownController.as 


package controller
{
import flash.display.MovieClip;
import model.DropDownModel;
import flash.events.Event;
import flash.net.URLLoader;
import flash.net.URLRequest;
public class DropDownController
{
private var _model : DropDownModel;
private var xmlLoader : URLLoader = new URLLoader;
private var xmlData:XML;
private var xmlAry:Array;
public function DropDownController(m:DropDownModel) 
{
_model = m;
xmlLoader.addEventListener(Event.COMPLETE, LoadXML);
xmlLoader.load(new URLRequest("books.xml"));
}
private  function LoadXML(e:Event):void 
{
xmlData = new XML(e.target.data);
xmlAry = new Array();
trace(xmlData..author.length());
var _nodeLen : int = xmlData..author.length();
for(var i:uint=0;i<_nodeLen;i++)
{
xmlAry.push(xmlData..author[i]);
}
_model.itemText = xmlAry;
trace(_model.itemText);
}
}
}

I have explained the Document class at last because to understand the above 3 classes structure and work separately. Now in our document class we have to mention all the classes one by one see below :

package
{
import flash.display.MovieClip;
import view.DropDownView;
import model.DropDownModel;
import controller.DropDownController;
public class Main extends MovieClip 
{
private var _model:DropDownModel;
private var _controller:DropDownController;
private var _view:DropDownView;
public function Main() 
{
// constructor code
_model = new DropDownModel;
_controller = new DropDownController(_model);
_view = new DropDownView(_model,_controller);
addChild(_view);
}
}
}


View is added after initializing the classes. So the final result will look like below image :


Monday 25 May 2015

Sprite Sheet Animation Using JavaScript and HTML5

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Sprite Sheet Animation</title>
</head>

<body>
<canvas id="myCanves" width="100" height="100">
<!-- Insert fallback content here -->
</canvas>
<script>
        var _width = 100;
var _height = 100;
var _frame = 4;
var _currentFrameCount = 0;
var ctx;

canvas = document.getElementById("myCanves");
ctx = canvas.getContext("2d");

var img = new Image();
img.src = "sprite.png";
img.onload = draw;

function draw ()
{
   ctx.clearRect(0, 0, _width, _height);   //to clear previously draw sprite before drawing new.
   ctx.drawImage(img, 0, _height * _currentFrameCount, _width, _height, 0, 0, _width, _height);  //to draw a sprite sheet with given height width and co-ordinates.

if(_currentFrameCount == _frame)
{
  _currentFrameCount = 0;
}
else
{
   _currentFrameCount++;
}
    }
setInterval(draw, 100);    // to call a draw function in a regular interval.

</script>
</body>
</html>

Equal Spacing between Dynamically created Textfields

private function createEqualSpacing(textfield : MovieClip, text : String, lastClip : MovieClip) : void
{
      (textfield.txt).text = text;
      (textfield.txt).multiline = true;
      (textfield.txt).width = 420;
      //Autosize textfield according to the text.
      (textfield.txt).autosize = TextFieldAutoSize.LEFT;
      (textfield.txt).border = true;

      if(lastClip != null)
      {
             textfield.y = lastClip.y + lastClip.height + 20;  //20 is fixed value space given between                                                                                                     //textfields.
      }
}


call the above function wherever required as below :

createEqualSpacing (mc1, xml.Text1, null);
createEqualSpacing (mc2, xml.Text2, mc2);
createEqualSpacing (mc3, xml.Text3, mc2);

Saturday 23 May 2015

Auto Resize font size of text inside textfield

Below function will be called as :

txtFieldFontResize (txtField, txtField.width, txtField.height);

private function txtFieldFontResize(txt:TextField, txtWidth : Number, txtHeight : Number):void
{
      //You set this according to your TextField's dimensions
      var maxTextWidth:int = txtWidth - 5; //(txtWidth == TextField.width)
      var maxTextHeight:int = txtWidth;

      var f:TextFormat = txt.getTextFormat();

     //decrease font size until the text fits
     while (txt.textWidth > maxTextWidth || txt.textHeight > maxTextHeight)
     {
                      f.size = int(f.size) - 1;
                      txt.setTextFormat(f);
      }
}


This code resize font size of textfield according to the text.

But there will be two things to keep in mind that :

1) Sometimes, after resizing font textfield will move up according to the ratio of font size decrement, So we need to set y position for this below while loop code block displayed above.

2) We need to set a limit of font size decrement, because suppose if font size will decrease till size 5 then user will not able to see that.

That's why we need to write few lines of code like,

if(f.size == 5)
{
     return;
}

I hope, my try is useful for few readers...
Happy Coding...:)


Microsoft Logo using flexbox and Reactjs

 <!DOCTYPE html> <html> <head>     <script src="https://unpkg.com/react@18/umd/react.development.js" crossori...