WeChat Mini Program API Drawing


wx.createContext()


Create and return the drawing context context object.

context

Context is just a container that records method calls and is used to generate an actions array that records drawing behavior. There is no corresponding relationship between context and <canvas/>. The drawing action array of a context-generated canvas can be applied to multiple <canvas/>.

// 假设页面上有3个画布
var canvas1Id = 3001;
var canvas2Id = 3002;
var canvas3Id = 3003;

var context = wx.createContext();

[canvas1Id, canvas2Id, canvas3Id].forEach(function (id) {
  context.clearActions();
  // 在context上调用方法
  wx.drawCanvas({
    canvasId: id,
    actions: context.getActions();
  });
});

Method list of context object:

MethodParametersDescription
getActionsNoneGet the drawing actions stored on the current context
clearActionsNoneClear the current stored drawing actions
Transformation
scale Yes Scale the horizontal and vertical coordinates
rotate Rotate the coordinate axis clockwise
translate Scale the coordinate origin
saveNoneSave the scaling of the current coordinate axis, Rotation and translation information
restoreNoneRestore the previously saved scaling, rotation and translation information of the coordinate axes
Draw
clearRect In the given rectangular area Within, clear the pixels on the canvas
fillText Draw the filled text on the canvas
drawImage Draw an image on the canvas
fillNoneFill the current path Fill
strokeNoneStroke the current path
Path
beginPathNoneStart a path
closePath NoneClose a path
moveTo Move the path to the specified point in the canvas , but no lines are created.
lineTo Adds a new point and then creates a line in the canvas from that point to the last specified point.
rect Add a rectangular path to the current path.
arc Add an arc path to the current path, drawn clockwise.
quadraticCurveTo Create a quadratic Bezier curve
bezierCurveTo Create cubic Bezier curve
Style
setFillStyle Set fill style
setStrokeStyle Set line style
setShadow Set shadow
setFontSize Set font Size
setLineCap Set the style of line endpoints
setLineJoin Set the style of the intersection of two lines
setLineWidth Set the line width
setMiterLimit Set the maximum tilt

Detailed explanation of the method:

scale

After calling the scale() method, the horizontal and vertical coordinates of the path created subsequently will be scaled. If scale is called multiple times, the multiples will be multiplied.

QQ截图20170208133838.png

//scale.js
<!--scale.wxml --> <canvas canvas-id="1" />
Page({
  onReady:function(e){
    var context = wx.createContext();
    context.rect(5,5,25,15)
    context.stroke();
    context.scale(2,2); //再放大2倍
    context.rect(5,5,25,15);
    context.stroke();
    context.scale(2,2); //再放大2倍
    context.rect(5,5,25,15)
    context.stroke();
    wx.drawCanvas({
      canvasId:1,
      actions:context.getActions()
    });
  }
})

201609261030525317.png

rotate

With the origin as the center, the origin can be modified using the translate method. Rotate the current coordinate axis clockwise. If rotate is called multiple times, the rotation angles will be superimposed.

##rotateNumberdegrees * Math.PI/180; degrees range is 0~360Rotation angle, in radians
ParametersTypeRangeDescription

Sample code:

//rotate.js
Page({
  onReady:function(e){
    var context = wx.createContext();
    context.rect(50,50,200,200)
    context.stroke();
    context.rotate(5*Math.PI/180)
    context.rect(50,50,200,200)
      context.stroke();
      context.rotate(5*Math.PI/180)
      context.rect(50,50,200,200)
      context.stroke()

    wx.drawCanvas({
      canvasId:1,
      actions:context.getActions()
    });
  }
})

201609261031438320.png

translate
For the current coordinate system The origin (0, 0) is used for transformation, and the default origin of the coordinate system is the upper left corner of the page.

ParametersTypeRangeDescription##xy
Number Horizontal coordinate translation amount
Number Vertical coordinate translation amount
Sample code:

//translate.js
Page({
  onReady:function(){
    var context = wx.createContext();

    context.rect(50,50,200,200)
    context.stroke()
    context.translate(50,50)
    context.rect(50,50,200,200)
    context.stroke();

    wx.drawCanvas({
      canvasId:1,
      actions:context.getActions()
    });
  }
})

201609261031553071.png

clearRect
Clear the content on the canvas within the rectangular area

Parameters##xNumberx coordinate of the upper left corner of the rectangular areaNumberNumberNumber
TypeRangeDescription
##y
y coordinate of the upper left corner of the rectangular areawidth
The width of the rectangular areaheight
The height of the rectangular area

Sample code:

//clearrect.js
Page({
  onReady:function(){
    var context = wx.createContext();

    context.rect(50,50,200,200)
    context.fill()
    context.clearRect(100,100,50,50)

    wx.drawCanvas({
      canvasId:1,
      actions:context.getActions()
    });
  }
})

201609261032093621.png

drawImage

Draws the image, keeping the original size of the image.

##imageResourceStringGet a file path or an image in a project directory through chooseImageThe image resource to be drawnxNumberx coordinate of the upper left corner of the imageyNumber The y coordinate of the upper left corner of the image
ParametersTypeRangeDescription
##Example:

//drawimage.js
Page({
  onReady:function(e){
    var context = wx.createContext();
    wx.chooseImage({
      success:function(res){
        context.drawImage(res.tempFilePaths[0],0,0)
        wx.drawCanvas({
          canvasId:1,
          actions:context.getActions()
        });
      }
    })
  }
})

201609261032277489.png
fillText

Draw filled text on the canvas.

Parameters##textStringText output on the canvasxNumber The x coordinate position of the upper left corner of the drawn textyNumberDraw the y coordinate position of the upper left corner of the textSample code:
TypeRangeDescription

//filltext.js
Page({
  onReady:function(){
    var context = wx.createContext();

    context.setFontSize(14)
    context.fillText("MINA",50,50)
    context.moveTo(0,50)
    context.lineTo(100,50)
    context.stroke();

    context.setFontSize(20)
    context.fillText("MINA",100,100)
    context.moveTo(0,100)
    context.lineTo(200,100)
    context.stroke();
    wx.drawCanvas({
      canvasId:1,
      actions:context.getActions()
    });
  }
})

201609261032388289.png
beginPath


To start creating a path, you need to call fill or stroke to use the path to fill or stroke. Multiple
setFillStyle
,

setStrokeStyle, setLineWidth and other settings within the same path, the last setting shall prevail. closePage

Close a path.
moveTo

Move the path to the specified point in the canvas without creating a line.

lineToQQ截图20170208134100.png

Adds a new point at the current location, then creates a path in the canvas from that point to the last specified point.

ParametersTypeRangeDescription##xNumberNumber
x coordinate of the target positiony
Y coordinate of the target position
rect

Add a rectangular path to the current path.

QQ截图20170208134149.png

arc

Adds an arc path to the current path, drawn clockwise.

QQ截图20170208134201.png
quadraticCurveTo

Create a quadratic Bezier curve path.

QQ截图20170208134211.png

bezierCurveTo

Create a cubic Bezier curve path.

QQ截图20170208134225.png

setFillStyle

Set a solid color fill.

Set color as fill style

ParametersTypeRange Description
colorString'rgb(255, 0, 0)'or'rgba( 255, 0, 0, 0.6)' or '#ff0000' format color stringSet as the color of the fill style
setStrokeStyle

Set a solid color stroke, the parameters are the same as setFillStyle.

Sample code:

//setfillstyle.js
Page({
  onReady:function(e){
    var context = wx.createContext();

    context.setFillStyle("#ff00ff");
    context.setStrokeStyle("#00ffff");

    context.rect(50,50,100,100)
    context.fill()
    context.stroke()
    wx.drawCanvas({
      canvasId:1,
      actions:context.getActions()
    });
  }
})

201609261032547620.png

setShadow

Set the shadow style.

QQ截图20170208134252.png
setFontSize

Set the font size.

QQ截图20170208134707.png
setLineWidth

Set the width of the line.

QQ截图20170208134718.png
setLineCap

Set the end point style of the line.

QQ截图20170208134736.png
setLineJoin

Set the corner type created when two lines intersect.

QQ截图20170208134745.png
setMiterLimit

Set the maximum miter length. The miter length refers to the distance between the inside and outside corners at the intersection of two lines. Valid only when setLineJoin is 'miter'. If the maximum slope length is exceeded, the connection will be displayed as lineJoin bevel

##miterLimitNumberMaximum miter length
ParameterTypeRangeDescription

Sample Code: Download

//line.js
Page({
  onReady:function(e){
    var context = wx.createContext();

    context.setLineWidth(10);
    context.setLineCap("round")
    context.setLineJoin("miter");
    context.setMiterLimit(10);
    context.moveTo(20,20);
    context.lineTo(150,27);
    context.lineTo(20,54);
    context.stroke();

    context.beginPath();

    context.setMiterLimit(3);
    context.moveTo(20,70);
    context.lineTo(150,77);
    context.lineTo(20,104);
    context.stroke();

    wx.drawCanvas({
      canvasId:1,
      actions:context.getActions()
    });
  }
})

201609261033171009.png

##wx.drawCanvas(OBJECT)

OBJECT parameter description:

QQ截图20170208134815.png##Example: Download

<!--canvas.wxml--><canvas cavas-id="firstCanvas" />
// index.js
Page({
  canvasIdErrorCallback: function (e) {

    console.error(e.detail.errMsg);
  },
  onReady: function (e) {

    //使用wx.createContext获取绘图上下文context
    var context = wx.createContext();

    context.setStrokeStyle("#00ff00");  
    context.setLineWidth(5);  
    context.rect(0,0,200,200);  
    context.stroke()
    context.setStrokeStyle ("#ff0000") ;
    context.setLineWidth (2)
    context.moveTo(160,100)
    context.arc(100,100,60,0,2*Math.PI,true);  
    context.moveTo(140,100);  
    context.arc(100,100,40,0,Math.PI,false);  
    context.moveTo(85,80);  
    context.arc(80,80,5,0,2*Math.PI,true);  
    context.moveTo(125,80);  
    context.arc(120,80,5,0,2*Math.PI,true);  
    context.stroke();  

    //调用wx.drawCanvas,通过canvasId指定在哪张画布上绘制,通过actions指定绘制行为
    wx.drawCanvas({
      canvasId: 'firstCanvas',
      actions: context.getActions() //获取绘图动作数组
    });
  }
});