新版
<!-- canvas.wxml -->
<canvas type="2d" id="myCanvas"></canvas>
// canvas.js
const query = wx.createSelectorQuery()
query.select('#myCanvas')
.fields({ node: true, size: true })
.exec((res) => {
const canvas = res[0].node
const ctx = canvas.getContext('2d')
const dpr = wx.getSystemInfoSync().pixelRatio
canvas.width = res[0].width * dpr
canvas.height = res[0].height * dpr
ctx.scale(dpr, dpr)
ctx.fillRect(0, 0, 100, 100)
})
var imgUrl = 'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1446459463,4116825017&fm=26&gp=0.jpg';
//将网络图片转成本地路径
wx.getImageInfo({
src: imgUrl,
success: function (res) {
// cav.drawImage(res.path, 0, 0, 375, 375)
console.log(res)
const img = canvas.createImage()
// img.src = '/assets/img/home-no-followed-icon.png'
img.src = res.path
img.onload = () => ctx.drawImage(img, 100, 100);
}
})
旧版
<!-- canvas.wxml -->
<canvas style="width: 300px; height: 200px;" canvas-id="firstCanvas"></canvas>
// canvas.js
// 在page获取
var ctx = wx.createCanvasContext('firstCanvas');
// 在组件中获取
var ctx = wx.createCanvasContext('firstCanvas', this);
context.setStrokeStyle("#00ff00")
context.setLineWidth(5)
context.rect(0, 0, 200, 200)
context.stroke()
context.setStrokeStyle("#ff0000")
context.setLineWidth(2)
context.moveTo(160, 100)
context.arc(100, 100, 60, 0, 2 * Math.PI, true)
context.moveTo(140, 100)
context.arc(100, 100, 40, 0, Math.PI, false)
context.moveTo(85, 80)
context.arc(80, 80, 5, 0, 2 * Math.PI, true)
context.moveTo(125, 80)
context.arc(120, 80, 5, 0, 2 * Math.PI, true)
context.stroke()
context.draw()
var imgUrl = 'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1446459463,4116825017&fm=26&gp=0.jpg';
ctx.drawImage(imgUrl, 0, 0, 65, 114)
ctx.draw(true,function(){
})
网友评论