Canvas

获取

<canva id="myCanvas"></canvas>

wx.createSelectorQuery().select('#myCanvas').node(res => {
      const ctx = res.node.getContext('2d');
})

 

替换原来的

wx.createCanvasContext('firstCanvass')

 

//绘制图
drawImage
例子:
// 二维码

wx.downloadFile({
  url: "http://192.168.0.133/immages/wechat.gif",
  success: function (res) {
    if (res.statusCode === 200) {
      ctx.drawImage(res.tempFilePath, winW-90, winH-90, 80, 80)
    }
  }
})


//绘制字
font
setTextBaseline
setTextAlign
fillStyle
fillText
例子:

ctx.font = "16px sans-serif";
ctx.setTextBaseline("top");
ctx.setTextAlign("left");        //(left,center,right是根据x轴定义的)
ctx.fillStyle = '#fff';
let fontHeight = 90
ctx.fillText('我在加里顿', winW - 200, fontHeight, 60);

 

beginPath
开始创建一个路径。需要调用 fill 或者 stroke 才会使用路径进行填充或描边
clostPath
关闭一个路径。会连接起点和终点。如果关闭路径后没有调用 fill 或者 stroke 并开启了新的路径,那之前的路径将不会被渲染。

其他方法:
setFontSize
strokeText(fillText)

setShadow
shadowBlur
shadowColor
shadowOffsetX
shadowOffsetY


// 开始绘制
ctx.draw()

 

1.绘制线

ctx.beginPath()     //创建新路径
ctx.moveTo(10, 10)
ctx.lineTo(100, 10)
ctx.lineTo(100, 100)
ctx.closePath()        //关闭路径后没有调用 fill 或者 stroke 并开启了新的路径,那之前的路径将不会被渲染
ctx.stroke()

 

2.绘制圆(实心或空心圆fill() / stroke())

  arc(number x, number y, number r, number sAngle, number eAngle, number counterclockwise)

 

3.绘制椭圆等

  arcTo(number x1, number y1, number x2, number y2, number radius)     ctx.moveTo(20,20); ctx.lineTo(100,20);一起用

 

4.绘制矩形(实心或空心圆fill() / stroke())

ctx.beginPath()
ctx.setFillStyle(color);
ctx.fillRect(x, y, w, h);
ctx.closePath()

  

 5. 转base64

var ext = image.src
.substring(image.src.lastIndexOf('.') + 1)
.toLowerCase();
var dataURL = canvas.toDataURL('image/' + ext);

 canvas.toDataURL(type, encoderOptions)

 6. 转二进制blob

 canvas.toBlob(callback, type, quality)

 

 

引擎three.js

THREE.WebGLRenderer 参数

 

 

 


 
微信小程序canvas绘制流程
// ①.初始化
let ctx = wx.createCanvasContext('id');    // canvas-id
// ②.绘制
ctx.draw();
// ③.保存为临时图片
wx.canvasToTempFilePath
// ④.查看是否授权相册
wx.getSetting  >  if (!res.authSetting['scope.writePhotosAlbum']) > wx.authorize({scope: 'scope.writePhotosAlbum',success (res) { console.log(res) }})
// ⑤.保存到相册
wx.saveImageToPhotosAlbum({})
wx.showLoading(); 
endDraw(ctx) {
    let that = this;
    ctx.draw(true, function (res) {
      console.log(res)
      setTimeout(()=>{
        wx.canvasToTempFilePath({
          // width: 750,
          // height,
          // destWidth: 750,
          // destHeight: height,
          canvasId: 'firstCanvass',
          fileType: 'jpg',
          quality: 1,
          success(res) {
            console.log('图片生成成功', res)
            let canvasPic = res.tempFilePath
            that.setData({
              canvasPic
            })
            wx.hideLoading();
            that.saveAlbum();
          },
          complete(res) {
            // console.log(res)
          }
        })
      },800)
    })
  },
// 保存到相册
  saveAlbum() {
    wx.hideLoading();
    let that = this;
    wx.saveImageToPhotosAlbum({
      filePath: this.data.canvasPic,
      success(result) {
        that.setData({
          altum: false
        })
        console.log('result', result)
        // console.log(result)
        setTimeout(function () {
          wx.showToast({
            title: '保存成功'
          })
        }, 500)
      },
      fail(error) {
        if(error &&  error.errMsg && error.errMsg.includes('cancel')) {
          wx.showToast({
            icon: 'none',
            title: '保存失败!',
          })
        } else {
          wx.showToast({
            icon: 'none',
            title: '保存失败,请再次点击授权相册!',
          })
          that.setData({
            altum: true
          })
        }
      }
    })
  },

  

 
 
 
 
 

微信小程序封装

①、#字体(换行)

/**
 * 字体
 * @param {CanvasContext} ctx canvas上下文
 * @param {string} sColor 字体颜色
 * @param {array} array 字体和位置(字体,字体x轴,y轴,换行宽度)
 * @param {string} align 字体居中(相对于x轴的)
 * @param {number} fontSize 字体大小
 */
export const fontDraw = function(obj, sColor, array, align, fontSize, lineHeight = 20) {
  obj.fillStyle = sColor;
  obj.setTextBaseline("top");
  obj.setTextAlign("left");
  if (fontSize) {
    obj.setFontSize(fontSize);
  }
  if (align) {
    obj.setTextAlign(align);
  }
  if (array.length > 120) {
    array.substr(0, 120);
  }
  let aArr = array;
 
  // 字体换行
  if (aArr[0]) {
    if (typeof aArr[0] == 'string') {
      var chr = aArr[0].split('');
    } else {
      var row = aArr[0];
      obj.fillText(row, aArr[1], aArr[2], aArr[3]);
      return;
    }
  } else {
    return;
  }
 
  var temp = "";
  var row = [];
  for (let a = 0; a < chr.length; a++) {
    // a的前一个为逗号,后两个为顿号时
    if (chr[a-1] == ',' && chr[a+2] == '、') {
      row.push(temp);
      temp = "";
      a = a + 1 // 去除逗号后面的空格
    } else if (obj.measureText(temp).width < aArr[3]) {
      // 全部字体长度加起来 小于 字体设置宽度 不做字体切割
    } else {
      // console.log(temp);
      row.push(temp);
      temp = "";
    }
    temp += chr[a];
  }
 
  row.push(temp);
  let endHeight = 0;
  for (let b = 0; b < row.length; b++) {
    endHeight = aArr[2] + b * lineHeight
    obj.fillText(row[b], aArr[1], aArr[2] + b * lineHeight, aArr[3]);
  }
  return endHeight
}
 
②、#绘制矩形
function rectDraw(obj, color, array, arrayShadow) {
  // obj.beginPath()
  obj.setFillStyle(color);
  if (arrayShadow) {
    obj.setShadow(arrayShadow[0], arrayShadow[1], arrayShadow[2], 
    arrayShadow[3]);
  } else {
    obj.setShadow(0, 0, 0, '#fff');
  }
  obj.fillRect(array[0] * 2, array[1] * 2, array[2] * 2, array[3] * 2);
  // obj.closePath();
  // obj.fill();
}

  

③、#绘制圆
function circleDraw(obj, color, array, type) {
  if (type == 'stroke') {
    obj.beginPath()
    obj.arc(array[0], array[1], array[2], array[3], array[4])
    obj.setStrokeStyle(color)
    obj.closePath()
    obj.stroke()
  } else {
    obj.beginPath()
    obj.setFillStyle(color)
    obj.setShadow(0, 0, 0, '#fff');
    obj.arc(array[0], array[1], array[2], array[3], array[4])
    obj.closePath()
    obj.fill()
  }
}

  

④、#绘制直线
function lineDraw(obj, color, array, width) {
  obj.beginPath()
  if (width) {
    obj.setLineWidth(width)
  }
  obj.moveTo(array[0], array[1])
  obj.lineTo(array[2], array[3])
  obj.stroke()
  obj.closePath()
}

 

⑤、#绘制圆形矩形

/**
   * 绘制圆角矩形
   * @param {*} ctx 画板上下文
   * @param {*} x 起始点x坐标
   * @param {*} y 起始点y坐标
   * @param {*} w 矩形宽
   * @param {*} h 矩形高
   * @param {*} r 圆角半径
   * @param {*} bg 背景色
   */
export const roundRect = function(ctx, x, y, w, h, r, bg='white') {
    ctx.beginPath()

    // 左上弧线
    ctx.arc(x + r, y + r, r, 1 * Math.PI, 1.5 * Math.PI)
    // 左直线
    ctx.moveTo(x, y + r)
    ctx.lineTo(x, y + h - r)
    // 左下弧线
    ctx.arc(x + r, y + h - r, r, 0.5 * Math.PI, 1 * Math.PI)
    // 下直线
    ctx.lineTo(x + r, y + h)
    ctx.lineTo(x + w - r, y + h)
    // 右下弧线
    ctx.arc(x + w - r, y + h - r, r, 0 * Math.PI, 0.5 * Math.PI)
    // 右直线
    ctx.lineTo(x + w, y + h - r)
    ctx.lineTo(x + w, y + r)
    // 右上弧线
    ctx.arc(x + w - r, y + r, r, 1.5 * Math.PI, 2 * Math.PI)
    // 上直线
    ctx.lineTo(x + w - r, y)
    ctx.lineTo(x + r, y)

    ctx.setFillStyle(bg)
    ctx.fill()
  }

 

 

 设置阴影影响全局?

posted @ 2019-02-14 14:38  Yo!  阅读(344)  评论(0编辑  收藏  举报