微信小程序·canvas 画布基本方法
微信小程序·canvas 画布
0】涂鸦
//html
<canvas class="canvas" style="height:{{Height}}px;width:{{Width}}px;" type="2d" id="canvas" bindtouchmove="move" bindtouchstart="start" > </canvas>//js-data 属性
pen: 2,
color: '#000fff',
canvas: '',
ctx: '',
first: true,//js-fun 画线
start(e) {
if (this.data.first) {
this.clearClick();
this.setData({
first: false
})
}
this.data.ctx.beginPath(); // 开始创建一个路径,如果不调用该方法,最后无法清除画布
this.data.ctx.moveTo(e.changedTouches[0].x, e.changedTouches[0].y) // 把路径移动到画布中的指定点,不创建线条。用 stroke 方法来画线条
},
move(e) {
this.data.ctx.lineTo(e.changedTouches[0].x, e.changedTouches[0].y) // 增加一个新点,然后创建一条从上次指定点到目标点的线。用 stroke 方法来画线条
this.data.ctx.stroke()
},
// 初始化Canvas
createCanvas() {
const query = wx.createSelectorQuery();
query.select('#canvas').fields({
node: true,
size: true
}).exec((res) => {
const canvas = res[0].node;
const ctx = canvas.getContext('2d');
canvas.width = this.data.Width; // 画布宽度
canvas.height = this.data.Height; // 画布高度
console.log(this.data.pen,this.data.color)
//ctx.scale(pr, pr); // 缩放比
ctx.lineGap = 'round'; //圆
ctx.lineJoin = 'round'; //圆
ctx.lineWidth = this.data.pen; // 字体粗细
// ctx.font = '40px Arial'; // 字体大小,
ctx.fillStyle = '#f00'; //设置字体颜色
ctx.strokeStyle = '#f00'; //线条边框颜色
//ctx.fillText('签名区', res[0].width, res[0].height)
this.setData({
ctx,
canvas
})
})
},
clearClick() {//清除画布
this.data.ctx.clearRect(0, 0, this.data.Width, this.data.Height);
// clearRect(线条位置x,线条位置y,画宽,画高)
},
1】设置背景图
var select = wx.createSelectorQuery();
select.select('#canvas').context(res => {
var ctx = res.context
ctx.setFillStyle("#FF0000")
//drawImage(image,sourceX,sourceY,sourceWidth,sourceHeight,x,y,width,height)
ctx.drawImage('../../static/cool.jpg', 200, 150, 160, 180, 70, 60, 160, 180); //图片
ctx.draw() //开始绘制
}).exec()2】保存图片
wx.canvasToTempFilePath({
canvasId: "canvas",
canvas: '',
fileType: 'png', //jpg 、png
width: 300, //指定画布区域
height: 300, //指定画布区域
x: 0, //指定画布区域的左上角横坐标
y: 0, //指定画布区域的左上角纵坐标
success(res) {
console.log("图片地址", res.tempFilePath);
}
})