canvas的width和style.width的区别

本文深入探讨了HTML5 Canvas元素的尺寸控制方法,包括如何通过HTML属性、CSS样式及JavaScript动态调整其宽度和高度,避免图像变形,确保画布与画纸尺寸匹配。

在canvas中,有width和height两个属性,它定以的是canvas的画布和画纸的大小。如果不设定,默认是300*150;
例如我们设置canvas的宽高都是300

<canvas id="demo" width="300" height="300"></canvas>

如下图,画布和画纸都是300,画面没有变形。
在这里插入图片描述

通过css设置canvas的width和height

<canvas id="demo" style="width: 300px;height: 300px;"></canvas>

这个时候修改的只是画布,画纸还是默认的300*150;

在这里插入图片描述
但是,画纸也不会让画布空出阴影那部分的。画纸会自动铺满画布。这样的话我们看到的图像就会发生变形。
在这里插入图片描述
怎么解决这个问题呢,我们可以通过js动态计算想要的canvas的尺寸,然后使用js操作canvas的width和height

var canvas = document.getElementById('欲操作canvas的id');
       canvas.width = 500;
       canvas.width = 500;


openScan() { const width = this.transtion(this.windowHeight) const height = this.transtion(this.windowWidth) const videoParam = { audio: false, video: { facingMode: { exact: this.exact }, width, height } } navigator.mediaDevices .getUserMedia(videoParam) .then(stream => { this.video = document.createElement('video') this.video.width = this.windowWidth this.video.height = this.windowHeight const canvas = document.createElement('canvas') canvas.id = 'canvas' canvas.width = this.transtion(this.canvasWidth) canvas.height = this.transtion(this.canvasHeight) canvas.style = 'display:none;' //canvas.style = 'position: fixed;top: 0;z-index: 999;left:0' this.canvas2d = canvas.getContext('2d') // 设置当前宽高 满屏 const canvasBox = document.querySelector('.canvasBox') canvasBox.append(this.video) canvasBox.append(canvas) canvasBox.style = `width:${this.windowWidth}px;height:${this.windowHeight}px;` // 创建第二个canvas const canvas2 = document.createElement('canvas') canvas2.id = 'canvas2' canvas2.width = this.canvasWidth canvas2.height = this.canvasHeight canvas2.style = 'position: absolute;top: 50%;left: 50%;z-index: 20;transform: translate(-50%, -50%);' this.canvas2d2 = canvas2.getContext('2d') canvasBox.append(canvas2) this.video.srcObject = stream this.video.setAttribute('playsinline', true) this.video.play() this.tick() this.track = stream.getVideoTracks()[0] setTimeout(() => { this.isUseTorch = this.track.getCapabilities().torch || null }, 500) }) .catch(err => { this.isUse = false this.$emit('error', err) }) },转换成vue3
04-02
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值