Canvas entry (3): Image Processing and drawing text, canvas Image Processing

Source: Internet
Author: User

Canvas entry (3): Image Processing and drawing text, canvas Image Processing

Source: http://www.ido321.com/997.html

I. Image Processing (Unless otherwise stated, all results are from the latest Google Version)

In HTML 5, you can not only use the Canvas API to draw images, but also process image files on networks or disks and then draw images on the Canvas. To draw an image, use the drawImage () method:

DrawImage (image, x, y): image is an image reference, and x and y are the starting position in the canvas when the image is drawn.

DrawImage (image, x, y, w, h): the first three are the same as above. w and h are the width and height of the image when being drawn. They can be used to scale the image.

DrawImage (image, sx, sy, sw, sh, dx, dy, dw. dh): Copies all or part of the drawn image to another position on the canvas. Sx, sy, sw, and sh indicate the start position and height of the copied area in the source image. dx, dy, dw, and dh indicate the start position and height of the copied image in the canvas.

1: // obtain the canvas ID
   2:     var canvas = document.getElementById('canvas');
   3:     if (canvas == null)
   4:     {
   5:         return false;
   6:     }
7: // obtain the context
   8:     var context = canvas.getContext('2d');
   9:     context.fillStyle = '#eeeeff';
  10:     context.fillRect(0,0,400,300);
  11:     var image = new Image();

12: image. src using 'my.jpg ';

// The onload event is used to draw and load edges.

  13:     image.onload = function()
  14:     {
  15:         drawImage(context,image);
  16:     };
  17:     function drawImage(context,image)
  18:     {
  19:         for (var i = 0; i < 7; i++) {
  20:             context.drawImage(image,0+i*50,0+i*25,100,100);
  21:         };
  22:     }

Effect:

1. image tile

1: // obtain the canvas ID
   2:     var canvas = document.getElementById('canvas');
   3:     if (canvas == null)
   4:     {
   5:         return false;
   6:     }
7: // obtain the context
   8:     var context = canvas.getContext('2d');
   9:     context.fillStyle = '#eeeeff';
  10:     context.fillRect(0,0,400,300);
  11:     var image = new Image();
  12:     image.src = 'my.jpg';
13: // onload event to achieve edge painting and Loading
  14:     image.onload = function()
  15:     {
  16:         drawImage(canvas,context,image);
  17:     };
  18:     function drawImage(canvas,context,image)
  19:     {
20: // tile Ratio
  21:         var scale = 5;
22: // reduce the Image Width
  23:         var n1 = image.width / scale;
24: // zoom down the Image Height
  25:         var n2 = image.height / scale;
26: // number of horizontal tiles
  27:         var n3 = canvas.width / n1;
28: // number of vertical tiles
  29:         var n4 = canvas.height / n2;
  30:         for(var i = 0; i < n3; i++)
  31:         {
  32:             for(var j=0; j < n4; j++)
  33:             {
  34:                 context.drawImage(image,i*n1,j*n2,n1,n2);
  35:             }
  36:         }
  37:     }

Effect:

In HTML 5, you can use context. createPattern (image, type) to tile. The value of type is the same as that of background-image.

   1: image.onload = function()
   2:     {
   3:         // drawImage(canvas,context,image);
   4:         var ptrn = context.createPattern(image,'repeat');
   5:         context.fillStyle = ptrn;
   6:         context.fillRect(0,0,400,300);
   7:     };

Can achieve the same tile (the image is not scaled, so the source image size is tiled)

2. Image Cropping

1: // obtain the canvas ID
   2:     var canvas = document.getElementById('canvas');
   3:     if (canvas == null)
   4:     {
   5:         return false;
   6:     }
7: // obtain the context
   8:     var context = canvas.getContext('2d');
9: // obtain the gradient object
  10:     var g1 = context.createLinearGradient(0,400,300,0);
11: // Add gradient color
  12:     g1.addColorStop(0,'rgb(255,255,0)');
  13:     g1.addColorStop(1,'rgb(0,255,255)');
  14:     context.fillStyle = g1;
  15:     context.fillRect(0,0,400,300);
  16:     var image = new Image();
17: // onload event to achieve edge painting and Loading
  18:     image.onload = function()
  19:     {
  20:         drawImage(context,image);
  21:     };
  22:     image.src = 'my.jpg';
  23:     function drawImage(context,image)
  24:     {
  25:         create5StarClip(context);
  26:         context.drawImage(image,-50,-150,300,300);
  27:     }
  28:     function create5StarClip(context)
  29:     {
  30:         var dx = 100;
  31:         var dy = 0;
  32:         var s  = 150;
33: // create a path
  34:          context.beginPath();
  35:          context.translate(100,150);
  36:          var x = Math.sin(0);
  37:          var y = Math.cos(0);
  38:          var dig = Math.PI/5 *4;
  39:          // context.moveTo(dx,dy);
  40:          for (var i = 0; i < 5; i++) {
  41:              var x = Math.sin(i * dig);
  42:              var y = Math.cos(i * dig);
  43:              context.lineTo(dx+x*s,dy+y*s);
  44:          }
  45:          context.clip();
  46:     }

Effect:

3. pixel Processing

1: // obtain the canvas ID
   2:     var canvas = document.getElementById('canvas');
   3:     if (canvas == null)
   4:     {
   5:         return false;
   6:     }
7: // obtain the context
   8:     var context = canvas.getContext('2d');
   9:     var image = new Image();
  10:     image.src = 'my.jpg';
11: // onload event to achieve edge painting and Loading
  12:     image.onload = function()
  13:     {
  14:         context.drawImage(image,0,0);
15: // obtain the source image pixel
  16:         var imageData = context.getImageData(0,0,image.width,image.height);
  17:         for (var i = 0,n= imageData.data.length; i <n; i += 4) {
  18:             // red
  19:             imageData.data[i+0] = 255-imageData.data[i+0];
  20:             // green
  21:             imageData.data[i+1] = 255-imageData.data[i+2];
  22:             // blue
  23:             imageData.data[i+2] = 255-imageData.data[i+1];
  24:         };
25: // apply the adjusted pixels to the image
  26:         context.putImageData(imageData,0,0);
  27:     };

GetImageData (sx, sy, sw, sh): obtains the starting coordinate and height of the pixel area. A CanvasPixelArray object with attributes such as width, height, and data is returned, the data attribute stores arrays of pixel data, such as [r1, g1, b1, a1, r2, g2, b2, a2…], R1, g1, b1, and a1 are the red, green, and Blue values and transparency of the first pixel, and so on.

PutImageData (imagedata, dx, dy [, dirtyx, dirtyy, dirtyWidth, dirtyHeight]): Re-draws the pixel data to the image. Imagedata is a pixel array. dx and dy indicate the starting position of the repainting. The following four parameters are the coordinates and width of the upper left corner of a rectangle.

The pixel operations of the Canvas API are only supported by some browsers. The effect is from the new Firefox browser.

Ii. Draw text

1: // obtain the canvas ID
   2:     var canvas = document.getElementById('canvas');
   3:     if (canvas == null)
   4:     {
   5:         return false;
   6:     }
7: // obtain the context
   8:     var context = canvas.getContext('2d');
   9:     context.fillStyle = '#00f';
10: // set text attributes
  11:     context.font = 'italic 30px sans-serif';
  12:     context.textBaseline = 'top';
13: // fill in the string
14: context. fillText ('canvas draw text', 0, 0 );
  15:     context.font = 'bold 30px sans-serif';
16: // contour string
17: context. strokeText ('changed location ', 50, 50 );

FillText (string, x, y [, maxwidth]): the first three values are not interpreted. maxwidth indicates the maximum width of the displayed text to prevent text overflow.

StrokeText (string, x, y [, maxwidth]: Same as above.

Text attribute settings

Font: Set the font

TextAlign: horizontal alignment. The value is start/end/left/right/center. The default value is start.

TextBaseline: vertical alignment. The value can be top/hanging/middle/alphabetic/ideographic/bottom. The default value is alphabetic.

Final Effect


Next article: 9 JQuery and 5 JavaScript classic interview questions



Hello, I want to teach you an html5 canvas problem: I drew multiple images in the canvas, including images and straight lines.

Canvas can be implemented
First, canvas must respond to mouse events (such as onmousedown)
Then, all images must create corresponding objects to record their locations and sizes, and zOrder (stacked positions, which determine who is on top when two objects overlap ), put the corresponding objects in an array and sort by zOrder
After the canvas mouse click event is triggered, the zOrder sequence is used to check that the mouse coordinates are not in the Area of an object. If the mouse coordinates are in the Area of an object, the corresponding function is executed.

Follow html5: can text be added to finished images through canvas text? Is there a demo video?

Each canvas object has a path object that defines the path outline. In this case, no path is displayed on the canvas screen. developers need to continue to call stroke ()/fill () function to complete the last step of rendering the path to the screen. The outline color and fill color of the path are determined by the strokeStyle and fillStyle attributes. You can also add text to the finished image using the canvas text. I recommend you to watch a video. For more information, search for "HTML5 new Vector Plotting function-Basic Canvas usage"

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.