发表于: 2015-07-21分类于:JavaScript

使用 canvas 进行图像处理


Drawing rectangles

  • fillRect(x, y, width, height): Draws a filled rectangle.
  • strokeRect(x, y, width, height):Draws a rectangular outline.
  • clearRect(x, y, width, height):Clears the specified rectangular area, making it fully transparent.

Drawing paths

  1. First, you create the path.
  2. Then you use drawing commands to draw into the path.
  3. Then you close the path.
  4. Once the path has been created, you can stroke or fill the path to render it.
  • beginPath():Creates a new path. Once created, future drawing commands are directed into the path and used to build the path up.
  • closePath():Closes the path so that future drawing commands are once again directed to the context.
  • stroke():Draws the shape by stroking its outline.
  • fill():Draws a solid shape by filling the path’s content area.

Moving the pen

  • moveTo(x, y)


  • lineTo(x, y)


  • arc(x, y, radius, startAngle, endAngle, anticlockwise)
  • arcTo(x1, y1, x2, y2, radius)

Bezier and quadratic curves

  • quadraticCurveTo(cp1x, cp1y, x, y)
  • bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)


  • rect(x, y, width, height)

Path2D objects

  • Path2D()
  • Path2D.addPath(path [, transform])


  • fillStyle:Sets the style used when filling shapes.
  • strokeStyle:Sets the style for shapes’ outlines.

Line styles

  • lineWidth = value

  • lineCap = type
  • lineJoin = type
  • miterLimit = value
  • getLineDash()
  • setLineDash(segments)
  • lineDashOffset = value


  • createLinearGradient(x1, y1, x2, y2)
  • createRadialGradient(x1, y1, r1, x2, y2, r2)


  • createPattern(image, type)
    • repeat:Tiles the image in both vertical and horizontal directions.
    • repeat-x:Tiles the image horizontally but not vertically. -repeat-y:Tiles the image vertically but not horizontally.
    • no-repeat:Doesn’t tile the image. It’s used only once.


  • shadowOffsetX = float
  • shadowOffsetY = float
  • shadowBlur = float
  • shadowColor = color

Drawing text

  • fillText(text, x, y [, maxWidth])
  • strokeText(text, x, y [, maxWidth])

Getting images to draw

  • Using images from the same page
  • Using images from other domains
  • Using other canvas elements
  • Creating an image from scratch
  • Embedding an image via data: URL
  • Using frames from a video

Drawing images

  • drawImage(image, x, y)
  • drawImage(image, x, y, width, height)
  • drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)

The ImageData object

  • width
  • height
  • data

Creating an ImageData object

var myImageData = ctx.createImageData(width, height);

Getting the pixel data for a context

var myImageData = ctx.getImageData(left, top, width, height);

Painting pixel data into a context

ctx.putImageData(myImageData, dx, dy);

Saving images

  • canvas.toDataURL(‘image/png’)
  • canvas.toDataURL(‘image/jpeg’, quality)
  • canvas.toBlob(callback, type, encoderOptions)