微信小程序 Canvas 画板使用,踩坑记录

2025-05-13 06:20:30 3d世界杯

微信小程序 Canvas 2dAPI的绘图使用

Html

type="2d"

id="canvas"

class='canvas-style'

/>

取消

保存图片

CSS

.canvas-style{

margin: 0 auto;

width: 100%;

height: 990rpx;

// border: 1px solid black;

}

.container{

z-index: 3;

position: fixed;

top:150rpx;

width: 100%;

height: 1100rpx;

// border: 1px solid red;

}

.container2{

position: fixed;

left:9950rpx;

width: 100%;

height: 1100rpx;

// border: 1px solid red;

}

.linkcopy{

width: 100%;

}

.linkcopyBtn{

display: inline-block;

float: left;

margin-top: 25rpx;

margin-left: 25rpx;

width: 45%;

height: 350rpx;

}

js

//初始化画板 - 微信小程序 canvas 2D

drawing(){

//定义全局canvas

const query = wx.createSelectorQuery();

query

.select('#canvas')

.fields({ node: true, size: true })

.exec((res) => {

const canvas = res[0].node;

this.canvasObj=canvas;

const ctx = canvas.getContext('2d');

const dpr = wx.getSystemInfoSync().pixelRatio;

canvas.width = res[0].width * dpr;

canvas.height = res[0].height * dpr;

this.canvasWidth=res[0].width * dpr;

this.canvasHeight = res[0].height * dpr;

ctx.scale(dpr, dpr);

// 填充一个白色矩形

ctx.fillStyle ='white';

ctx.fillRect(8, 55, 345,425);

//头部图片

const headerImg = canvas.createImage();

headerImg.src = this.TopList.product_image_url;

headerImg.onload = () => {

ctx.drawImage(headerImg, 83, 65, 200, 186);

};

// 标题

ctx.fillStyle ='#333333';

ctx.font = 'normal bold 15px sans-serif';

ctx.fillText(this.TopList.brand_name+" | "+this.TopList.gpc_product.FNAME+" | "+this.TopList.gpc_product.FSPECIFICATION, 20, 270);

// 二维码

const QRcodeImg = canvas.createImage();

QRcodeImg.src = this.QRcodeImg;

QRcodeImg.onload = () => {

ctx.drawImage(QRcodeImg, 215, 345, 124.5, 130);

};

//logo

const logoImg = canvas.createImage();

logoImg.src = this.logoImg;

logoImg.onload = () => {

ctx.drawImage(logoImg, 25, 345, 180, 80);

};

})

},

截图保存分享

//下载画板生成图片

uploads() {

var that = this;

var timer = setTimeout(function(){

wx.canvasToTempFilePath({

x: 8,

y: 55,

width: 345,

height: 425,

destWidth: this.canvasWidth,

destHeight: this.canvasHeight,

canvas: that.canvasObj,

success(res) {

wx.saveImageToPhotosAlbum({

filePath: res.tempFilePath,

success: function (data) {

wx.showToast({

title: '保存成功,快去分享吧',

icon: 'none',

duration: 2000

});

that.showCanvas=false;

that.showCanvasCSS="container2";

clearTimeout(timer);

},

fail: function (error) {

console.log(error)

wx.showToast({

title: '很遗憾,保存失败',

icon: 'none',

duration: 2000

})

clearTimeout(timer)

}

})

}

})

},1000)

}

注:需要注意的是,对于Canvas画板需要隐藏/显示,运用wx:if 、v-if、v-show、hidden都不可行,解决方案为将canvas设置定位,比如,然后指定left一个比较大的值,让canvas的显示超出屏幕范围。

微信小程序 Canvas 旧版API的绘图使用 鉴转载:

https://blog.csdn.net/javascript411/article/details/95466716

这个纹身是什么意思?
甜票直播iOS版下载