Use HTML5 and JavaScript to create a drawing application-

Source: Internet
Author: User
Let's create a web application that allows you to dynamically draw images on html5canva labels. What tools will our users need? The first thing I think of in my mind is the coloring book, which is colored with crayons, so the first tool is crayons. Although in the real world, there is no way to wax ...,. Let's create a web application that allows you to dynamically draw images on html5 canva labels. Our users
What tools will be used? The first thing I think of in my mind is the coloring book, which is colored with crayons.
A tool is a crayon. Although there is no way to erase crayons in the real world, I think our application needs to be able to erase them.
Drop the crayons, so the second tool is to wipe the cloth. Because I am a SharpieR fan (translated as a stationery brand), so our last
Tools will be a singularity.

Our tool should be able to select colors (except for cloth). To keep it simple, we only open four colors.
Select from them for our users.

In the same place, we also provide four sizes for the user to plot and summarize the elements that our application should have:

* 3 tools: crayons, kiwi pens, and cloths
* Four colors for selection
* Four Application sizes

Just like a coloring book, let's give users a coloring object. My favorite is:
The Watermelon Duck of Rachel Cruthirds ).

Prepare HTML5 Canvas: marker

Only one line of code can be used to create the canvas flag element: others will be implemented using scripts.

 

... HTML5 is still a new technology, and some browsers (?... That is, your IE) does not support
Canvas label, so use the following code instead:


Prepare HTML5 Canvas: script writing

In order to use our canvas element, we hope to obtain the canvas context content through its id for access:

context = document.getElementById('canvasInAPerfectWorld').getContext("2d");


However, IE does not parse the canvas tag, So if you use the labeled method IE, it will be handled with errors.

The alternative solution is to use JavaScript to create a canvas element and then attach it to our canvasDiv p.

var canvasDiv = document.getElementById('canvasDiv');canvas = document.createElement('canvas');canvas.setAttribute('width', canvasWidth);canvas.setAttribute('height', canvasHeight);canvas.setAttribute('id', 'canvas');canvasDiv.appendChild(canvas);if(typeof G_vmlCanvasManager != 'undefined') {    canvas = G_vmlCanvasManager.initElement(canvas);}context = canvas.getContext("2d");


Internet Explorer compatibility we will also have to include an additional script: assumercanvas.

To solve IE compatibility problems, we must add additional scripts:

Assumercanvas


Basic Drawing functions of chuangjian:

Before we add various options, let's first complete the basic functions of HTML5 canvas dynamic drawing. This part
It contains four mouse events and two functions: addClick () to record mouse data,
The redraw () function will plot the data.

Mouse Down event: When you click canvas, the Mouse position is directed by the addClick () function.
Record it in an array and set a paint brang variable to true (will be explained later ). Finally, I
Use the redraw () function to update the canvas.

$('#canvas').mousedown(function(e){      var mouseX = e.pageX - this.offsetLeft;      var mouseY = e.pageY - this.offsetTop;      paint = true;      addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);      redraw();});


Mouse Move event: Just like moving the pen tip on the paper, when you press and hold the left button, we want to draw it on the canvas. The brang variable paint allows us to know whether the virtual pen is in the touch of paper or in the air.

If the paint value is true, the mouse data is recorded and drawn.

$('#canvas').mousemove(function(e){  if(paint){    addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);    redraw();  }});


Mouse Up event: the pen tip leaves the paper; the paint brang variable is responsible for recording.

$('#canvas').mouseup(function(e){  paint = false;});


Mouse Leave event: if the pen tip leaves the area of the paper, it will make us forget your existence, so we also set the paint to false.

$('#canvas').mouseleave(function(e){  paint = false;});


The following is the implementation of the addClick function, which is used to record the position where the mouse is pressed:

var clickX = new Array();var clickY = new Array();var clickDrag = new Array();var paint;function addClick(x, y, dragging){  clickX.push(x);  clickY.push(y);  clickDrag.push(dragging);}

The redraw () function is where magic occurs. When redraw () is called, the entire canvas is cleared and the mouse data is re-drawn.
In fact, we can just re-draw a new area, which is more efficient, but we still make things easier.
We set some Pen attributes, colors, shapes, and widths.
Then we draw the record's mouse data, draw a line from the first data to the second position, and so on.

function redraw(){  canvas.width = canvas.width; // Clears the canvas    context.strokeStyle = "#df4b26";  context.lineJoin = "round";  context.lineWidth = 5;                          for(var i=0; i < clickX.length; i++)  {                    context.beginPath();    if(clickDrag[i] && i){      context.moveTo(clickX[i-1], clickY[i-1]);     }else{       context.moveTo(clickX[i]-1, clickY[i]);     }     context.lineTo(clickX[i], clickY[i]);     context.closePath();     context.stroke();  }}


Add Size Option

Just like adding color options, let's add some selectable sizes: small, medium, large, and super large.

We also need a set of global variables: clickSize array and curSize to store the current size selection.

var clickSize = new Array();var curSize = "normal";


The addClick () function also needs to change. Each time a user clicks, the selected size is recorded.

function addClick(x, y, dragging){  clickX.push(x);  clickY.push(y);  clickDrag.push(dragging);  clickColor.push(curColor);  clickSize.push(curSize);}


Modify the redraw () function to support the brush size setting.

function redraw(){  context.lineJoin = "round";  class="highlight delete">/* context.lineWidth = 5; */  for(var i=0; i < clickX.length; i++)  {                    context.beginPath();    if(clickDrag[i] && i){      context.moveTo(clickX[i-1], clickY[i-1]);    }else{      context.moveTo(clickX[i]-1, clickY[i]);    }    context.lineTo(clickX[i], clickY[i]);    context.closePath();    context.strokeStyle = clickColor[i];    context.lineWidth = radius;    context.stroke();  }}


Add Tool

Let's implement crayons, kips, and cloths.

We need two new global variables: clickTool and curTool.

var clickTool = new Array();var curTool = "crayon";


First modify the addClick () function. When you select a tool, record its value.


function addClick(x, y, dragging){  clickX.push(x);  clickY.push(y);  clickDrag.push(dragging);  if(curTool == "eraser"){    clickColor.push("white");  }else{    clickColor.push(curColor);  }  clickColor.push(curColor);  clickSize.push(curSize);}

  1. You can also change the redraw () function to support new tools.

function redraw(){  context.lineJoin = "round";  for(var i=0; i < clickX.length; i++)  {                    context.beginPath();    if(clickDrag[i] && i){      context.moveTo(clickX[i-1], clickY[i-1]);    }else{      context.moveTo(clickX[i]-1, clickY[i]);    }    context.lineTo(clickX[i], clickY[i]);    context.closePath();    context.strokeStyle = clickColor[i];    context.lineWidth = radius;    context.stroke();  }  if(curTool == "crayon") {    context.globalAlpha = 0.4;    context.drawImage(crayonTextureImage, 0, 0, canvasWidth, canvasHeight);  }  context.globalAlpha = 1;}


Add a contour Pattern

The coloring book will provide a contour pattern for us to color, such as cute puppies or jumping rabbits, while I choose watermelon ducklings...

First, declare the outlineImage pattern variable.

var outlineImage = new Image();


Load profile image

function prepareCanvas(){  ...    outlineImage.src = "images/watermelon-duck-outline.png";}


Change our redraw () function and use the drawImage () method of the canvas attribute context to draw our profile.

Parameters of the drawImage () function: The image object we load. We want to draw the vertical and horizontal positions of the profile and its length and width.

function redraw(){  ...    context.drawImage(outlineImage, drawingAreaX, drawingAreaY, drawingAreaWidth, drawingAreaHeight);}


Final details

Close to our application, the final details are optional: Restrict square areas that can be painted and use other locations to create our GUI (buttons)

By shielding the canvas element, the drawing is displayed only in the area of the drawing paper. This implementation uses the clip (), save (), and restore methods. Currently, IE does not support these methods.



function redraw(){  ...    context.save();  context.beginPath();  context.rect(drawingAreaX, drawingAreaY, drawingAreaWidth, drawingAreaHeight);  context.clip();    var radius;  var i = 0;  for(; i < clickX.length; i++)  {    ...   }  context.restore();  ...} // end redraw function

  1. In the last step, add a button. This includes loading the button pattern and then displaying it for interaction. I am using the standard JavaScript technology for this implementation, so I will not waste it. (If you want to know, you can check it in the source code ). The above is the entire tutorial.

The above section uses HTML 5 and JavaScript to create a drawing application. For more information, see PHP Chinese website (www.php1.cn )!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.