正式项目中绘制传入宽高小于画布很多,其实仍然不能正确拉伸,只不过能看到全部,图片大小是800x551
canvas绘制图片,传入绘制的宽高无法正确拉伸?canvs绘制图片画布大小为动态设置,然后让图片拉伸填满画布,代码片段上宽度正确拉伸,高度无法正确拉伸,画布大小不动态设置可以正确拉伸,正式项目中宽高都不能正确拉伸,画布大小写死也是如此。但是正式项目只有绘制图片时传入小于画布大小很多才能正确拉伸。 代码片段代码: init(res) { const width = res[0].width const height = res[0].height const canvas = res[0].node const ctx = canvas.getContext('2d') const img = canvas.createImage() console.log(width,height); img.src = 'mapc.png' img.onload = () => { this._img = img ctx.drawImage(img, 0, 0, width, height) } // console.log(this._img); }, /** * 生命周期函数--监听页面显示 */ onShow() { this.setData({ w:300, h:200 }) wx.createSelectorQuery() .select('#canvas') .fields({ node: true, size: true, }) .exec(this.init.bind(this)) }, html代码 <image src="./mapc.png"></image> <canvas type="2d" id="canvas" style="width: {{w}}px; height: {{h}}px;" ></canvas> 效果如下: [图片]动态设置画布大小,高度无法正确拉伸 [图片]画布大小设置写死300x300正确拉伸 正式项目代码: drawMap (params) { wx.createSelectorQuery() .select('#canvas') .fields({ node: true, size: true, }) .exec(this.init.bind(this)) }, init(res){ console.log(res); const width = res[0].width const height = res[0].height const canvas = res[0].node const ctx = canvas.getContext('2d') const img = canvas.createImage() img.src = '../../assets/image/mapc.png' img.onload = () => { this._img = img console.log(img.width); console.log(this._img); console.log(width,height); ctx.drawImage(img,0,0,width,height) } }, /** * 生命周期函数--监听页面显示 */ onShow: function () { let that = this let query = wx.createSelectorQuery() query.select(".map").boundingClientRect(res=>{ console.log(res); that.setData({ imgT:res.top, imgL:res.left, imgW:res.width, imgH:res.height, }) this.drawMap() }).exec() }, html代码 <canvas id="canvas" style="width: {{imgW}}px; height: {{imgH}}px;" type="2d" canvas-id="canvas"></canvas> 效果如下: [图片]动态设置画布大小 [图片]画布设置414x240其他不变 [图片]画布大小设置414x240,绘制大小传入300x100
2022-04-27