swan.canvasToTempFilePath

解释:把当前画布指定区域的内容导出生成指定大小的图片,并返回文件路径。在自定义组件下,第二个参数传入组件实例this,以操作组件内<canvas/>组件。

方法参数

Object object

object参数说明

属性名类型必填默认值说明
xNumber0指定的画布区域的左上角横坐标
yNumber0指定的画布区域的左上角纵坐标
widthNumbercanvas宽度-x指定的画布区域的宽度
heightNumbercanvas高度-y指定的画布区域的高度
destWidthNumberwidth 屏幕像素密度输出图片宽度
destHeightNumberheight 屏幕像素密度输出图片高度
canvasIdString画布标识,传入<canvas/>的 canvas-id
fileTypeStringpng目标文件的类型,有效值只支持 'jpg' 或 'png' 。
qualityNumber图片的质量,取值范围为 (0, 1],不在范围内时当作 1.0 处理 。
successFunction接口调用成功的回调函数
failFunction接口调用失败的回调函数
completeFunction接口调用结束的回调函数(调用成功、失败都会执行)

示例

扫码体验

swan.canvasToTempFilePath - 图1请使用百度APP扫码

图片示例

swan.canvasToTempFilePath - 图2

swan.canvasToTempFilePath - 图3

swan.canvasToTempFilePath - 图4

代码示例 1

在开发者工具中预览效果

请使用2.7.0-beta及其以上版本swan.canvasToTempFilePath - 图5进行预览,正式版将在2.6.1以上版本支持。

  1. <canvas canvas-id="myCanvas" />
  2. <button type="primary" bindtap="canvasToTempFilePath">canvasToTempFilePath</button>
  3. <image src="{{src}}"></image>
  1. Page({
  2. data: {
  3. src: ''
  4. },
  5. onReady: function () {
  6. const canvasContext = this.createCanvasContext('myCanvas');
  7. canvasContext.setFillStyle('#ff0000');
  8. canvasContext.arc(100, 50, 50, 0, 2 * Math.PI);
  9. canvasContext.fill();
  10. canvasContext.draw();
  11. },
  12. canvasToTempFilePath (){
  13. const that = this;
  14. swan.canvasToTempFilePath({
  15. x: 0,
  16. y: 0,
  17. width: 300,
  18. height: 225,
  19. destWidth: 300,
  20. destHeight: 225,
  21. canvasId: 'myCanvas',
  22. success: function(res){
  23. that.setData("src", res.tempFilePath);
  24. swan.showModal({
  25. title: '图片路径',
  26. content: JSON.stringify(res.tempFilePath)
  27. })
  28. }
  29. })
  30. }
  31. })

代码示例 2:在draw中使用

在开发者工具中预览效果

请使用2.19.0-rc及其以上版本swan.canvasToTempFilePath - 图6进行预览,正式版将在2.18.1(不包括2.18.1)以上版本支持。

  1. <canvas canvas-id="myCanvas" />
  2. <image src="{{src}}"></image>
  1. Page({
  2. data: {
  3. src: ''
  4. },
  5. onReady: function () {
  6. let that = this;
  7. const canvasContext = this.createCanvasContext('myCanvas');
  8. canvasContext.setFillStyle('#ff0000');
  9. canvasContext.arc(100, 50, 50, 0, 2 * Math.PI);
  10. canvasContext.fill();
  11. canvasContext.draw(function() {
  12. swan.canvasToTempFilePath({
  13. x: 0,
  14. y: 0,
  15. width: 300,
  16. height: 225,
  17. destWidth: 300,
  18. destHeight: 225,
  19. canvasId: 'myCanvas',
  20. success: function(res){
  21. that.setData("src", res.tempFilePath);
  22. swan.showModal({
  23. title: '图片路径',
  24. content: JSON.stringify(res.tempFilePath)
  25. })
  26. }
  27. })
  28. });
  29. }
  30. })

错误码

Android

错误码说明
201解析失败,请检查调起协议是否合法
1001执行失败

iOS

错误码说明
202解析失败,请检查参数是否正确

Bug & Tip

  • 在 draw 回调里调用该方法才能保证图片导出成功。
  • 当 x < 0 或者 x > canvase.width 时,x 会被置成0,y 同理。
  • 当 x 合法的前提下,若 x + width > canvas.width 时, width 会被置成 canvas.width - x,y 同理。