1. html
< canvas class = " canvas" id = " photo" type = " 2d" style = " width : 200px; height : 300px; " > </ canvas>
< button bindtap = " saveImage" > 保存</ button>
< image src = " {{tempFilePath}}" mode = " widthFix" />
2. js
data : {
canvas : null ,
tempFilePath : ""
} ,
onLoad ( options ) {
wx. createSelectorQuery ( )
. select ( '#photo' )
. fields ( {
node : true ,
size : true
} )
. exec ( ( res ) => {
const canvas = res[ 0 ] . node
this . setData ( {
canvas
} )
const ctx = canvas. getContext ( '2d' )
const width = res[ 0 ] . width
const height = res[ 0 ] . height
const dpr = wx. getWindowInfo ( ) . pixelRatio
canvas. width = width * dpr
canvas. height = height * dpr
ctx. scale ( dpr, dpr)
ctx. clearRect ( 0 , 0 , width, height)
ctx. fillStyle = '#3c9cff' ;
ctx. fillRect ( 0 , 0 , 200 , 300 ) ;
const image = canvas. createImage ( )
image. src = '/images/640.png'
image. onload = ( ) => {
ctx. drawImage ( image, 0 , 0 , 200 , 300 )
}
} )
} ,
saveImage ( ) {
wx. canvasToTempFilePath ( {
canvasId : 'photo' ,
destWidth : 286 ,
destHeight : 417 ,
canvas : this . data. canvas,
success : ( res ) => {
this . setData ( {
tempFilePath : res. tempFilePath
} )
wx. saveImageToPhotosAlbum ( {
filePath : res. tempFilePath,
success : ( res ) => {
wx. showToast ( {
title : '保存成功' ,
} )
}
} )
}
} ) ;
} ,
3. css
.canvas {
margin : auto;
font-size : 0;
}
.show {
width : 200px;
margin : auto;
display : block;
}
4. 效果图