调整Canvas html的大小以适应内部内容



我正在尝试录制音频并在画布上绘制条形图。但我一直在根据条形图的长度调整画布的大小。以下是所有正在进行的工作的JS。我尝试添加函数来调整画布大小,并覆盖画布宽度,但都不起作用。css宽度:auto;也不起作用。以下是我用来根据绘制的BARS长度调整画布大小的函数。我试图覆盖停止函数内的画布宽度[Current Visual of Bars in canvas][1]

以下代码可以在此代码笔中进行测试https://codepen.io/smashingmag/pen/qBVzRaj

function resizeCanvas() {
CANVAS.width = BARS.length;
console.log(CANVAS.width);
}
resizeCanvas();

//Getting and initializing canvas from html to create bars 
const CANVAS = document.querySelector('canvas')
const DRAWING_CONTEXT = CANVAS.getContext('2d')
//setting canvas height and width and bars configuration
CANVAS.width = CANVAS.offsetWidth
CANVAS.height = CANVAS.offsetHeight

const CONFIG = {
fft: 2048,
show: true,
duration: 0.8,
fps: 100,
barWidth: 0.1,
barMinHeight: 0.01,
barMaxHeight: 0.3,
barGap: 0.01,
}
//here I am creating bars
const addBar = (volume = 100) => {
const BAR = {
x: CANVAS.width + CONFIG.barWidth / 2,
// Note the volume is 0
size: gsap.utils.mapRange(
50,
150,
CANVAS.height * CONFIG.barMinHeight/3,
CANVAS.height * CONFIG.barMaxHeight*3
)(volume),
}
const drawBars = () => {
DRAWING_CONTEXT.clearRect(0, 0, CANVAS.width, CANVAS.height)
for (const BAR of BARS) {
drawBar(BAR)
}
}
STOP.addEventListener('click', () => {
if (recorder) recorder.stop()
AUDIO.setAttribute('controls', true)
AUDIO_CONTEXT.close()
timeline.pause()
SCRUB(START_POINT)
var delayInMilliseconds = 1000; //1 second
setTimeout(function() {
//Here i am getting the canvas image on console

const img =  CANVAS.toDataURL("image/png");  
console.log(img);
}, delayInMilliseconds);
})
drawBars()
[1] :https://i.stack.imgur.com/JBBjT.png

我看了你的代码笔,我认为你的有一个简单的解决方案

function resizeCanvas() {
CANVAS.style.width = BARS.length + "px";
CANVAS.width = BARS.length;
}

这只是使用javascript设置CSSwidth属性。

执行CANVAS.width = 500不会覆盖CSS,因为CSS告诉它是300px。所以这仍然是一个CSS问题。

最新更新