请问大神们,为什么canvas不能动态设置大小
发布于 4 年前 作者 vxiao 7954 次浏览 来自 问答

您好!大神!!!

我想通过canvas生成缩略图,但是老是只生了图片的一部份 (客户端 IPHONE7有此问题  开发者工具不会出现这个问题)

WXML

<canvas canvas-id=“shareCanvas” style=" top:-{{cavHeight}}px;left:-{{cavWidth}}px;   width:{{cavWidth}}px;height:{{cavHeight}}px;background:#ccc;"></canvas>

JS

1.设置默认大小

data: {

PicUrl: “”,

cavWidth:100,

cavHeight:100,

pixelRatio: device.pixelRatio

},

2.选择图片后自动调整画布大小

wx.getImageInfo({

src: PicUrl,

success: function(res) {

console.log(res);

const ctx = wx.createCanvasContext(‘shareCanvas’)

console.log(“画布信息”);

console.log(ctx);

var cavWidth = res.width;// / device.pixelRatio;

var cavHeight = res.height;// / device.pixelRatio;

console.log(“画布宽度:”+ctx.width+“px 高度:”+ctx.height);

console.log(“图片宽度:” + res.width + “px 高度:” + res.height);

console.log(ctx);

page.setData({

cavWidth: cavWidth,

cavHeight: cavHeight

})

最终客户端只显示 了图片的一部份

就是canvas的默认值  

cavWidth:100,

cavHeight:100,

而代码

page.setData({

cavWidth: cavWidth,

cavHeight: cavHeight

})

并没有生效  抓狂了,谢谢大神们指引一下

3 回复

<canvas

    canvas-id=“shareCanvas”

    ___width="{{cavWidth}}"
___

    height="{{cavHeight}}"

    style=" top:-{{cavHeight}}px;left:-{{cavWidth}}px;   width:{{cavWidth}}px;height:{{cavHeight}}px;background:#ccc;">

</canvas>

在给canvas设置宽高的setData的回调方法里画图。。如果还需要直接存图,还要setTimeout一下

回到顶部