比如原生html
Title
function start() {
let canvas = document.querySelector('.canvas');
let ctx = canvas.getContext('2d');
canvas.width = 500; // 设置宽度
canvas.height = 900; // 设置高度
}
start()
可以设置画布的宽高,小程序里面怎么用js 控制呢?
<!-- canvas.wxml -->
<canvas type="2d" id="myCanvas"></canvas>
// canvas.js
Page({
onReady() {
const query = wx.createSelectorQuery()
query.select('#myCanvas')
.fields({ node: true, size: true })
.exec((res) => {
const canvas = res[0].node
canvas.width = res[0].width * dpr
canvas.height = res[0].height * dpr
})
}
})
z
这样设置了没用呀
async drawCanvas(){
// 取 canvas 节点
// 此处使用 await
let canvasNode = await new Promise((resolve, reject)=>{
// 注意:若canvas是定义在在组件内,需改用
// const query = wx.createSelectorQuery().in(this)
const query = wx.createSelectorQuery()
query.select('#canvas')
.fields({ node: true, size: true })
.exec(res=>{
resolve(res[0])
})
})
let canvas = canvasNode.node,
ctx = canvas.getContext('2d')
this.canvas = canvas
this.ctx = ctx
canvas.width = width
canvas.height = height
}
在外面拿到节点设置还是不行呀
canvas标签有width和height属性的