canvas生成水印图,并且存图分享

 h5存图分享

css属性可用于存图分享:-webkit-touch-callout:default;

html:

<canvas id="myCanvas" style="display:none;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<img src="" id="imga">

 

var img,//图片对象
imgIsLoaded,//图片是否加载完成;
imgX = 0,
imgY = 0;
(function int() {
    canvas = document.getElementById('myCanvas'); //画布对象
    canvas.width = screen.width;
    canvas.height = screen.height;
    context = canvas.getContext('2d');//画布显示二维图片
    loadImg();
})();
function loadImg() {
    img = new Image();
    img.onload = function () {
        imgIsLoaded = true;
        drawImage();
    }
    img.src = './images/shareImg.png';
}
function drawImage() {
    context.clearRect(0, 0, canvas.width, canvas.height);
    var imgWidth = canvas.width;
    var imgHeight = (canvas.width*img.height)/img.width;
    context.drawImage(
        img, //规定要使用的图像、画布或视频。
        0, 0, //开始剪切的 x 坐标位置。
        img.width, img.height, //被剪切图像的高度。
        imgX, imgY,//在画布上放置图像的 x 、y坐标位置。
        imgWidth,imgHeight //要使用的图像的宽度、高度
    );
    context.fillStyle = "#fbba15";
    context.font = "35px microsoft yahei";
    context.fillText(level*level,255,210);
    context.fillText(score+"秒",164,280);

    //注意跨域问题
    $("#imga").attr('src',canvas.toDataURL())
}

            

 

 

微信存图:

wxml:
<button id="saveImg" style="background: #fe6659;" bindtap='createNewImg'>存图分享</button>

<canvas canvas-id='canvasimg' style='height:1336px;'></canvas>

wxss:
canvas{position: absolute;top: 0px;left: -1000px;width: 754px;} 

js:

createNewImg: function () {
    var that = this;
    wx.showToast({
      title: '分享图片生成中...',
      icon: 'loading',
      mark: false,
      duration: 1000
    });
    var numLeft = 485;
    var bgWidth = that.data.bgWidth;
    var winHeight = that.data.winHeight;
    var level = that.data.level;
    var score = that.data.score;
    if (level == 3) {
      numLeft = 510;
    }
    var ctx = wx.createCanvasContext('canvasimg', that);
    ctx.drawImage('../../../../pic/shareImg.png', 0, 0, 754, 1336);
    ctx.setFontSize(70);
    ctx.setFillStyle("#fbba15");
    ctx.fillText(level * level, numLeft, 420);
    ctx.setFontSize(60);
    ctx.fillText(score + "秒", 325, 560); 
    ctx.draw(false, function () {
      wx.canvasToTempFilePath({
        canvasId: 'canvasimg',
        success: function (res) { 
          var tempFilePath = res.tempFilePath;
          wx.previewImage({
            current: tempFilePath,
            urls: [tempFilePath]
          })
          wx.hideToast();
        }
        , fail: function (res) {
          console.log('ERROR');
          console.log(res);
        }
      });
    });
  },

 

posted @ 2018-01-15 15:37  wanpisces  阅读(216)  评论(0编辑  收藏  举报