我是fabricjs新手,我正在尝试实现以下目标:拥有一个特定尺寸的画布(假设为600px),但在浏览器上它应该在视觉上显示较小(假设为300px)。
当我将其下载为 png 图像时,它的宽度应为 600 像素,即使在屏幕上其尺寸(视觉上)为 300 像素
这是我的小提琴:
https://jsfiddle.net/82av0coh/1/
<div style="width:300px">
<canvas id="mycanvas" width="600"></canvas>
</div>
如您所见,画布设置为 600px,父级设置为 300px,但画布会扩展而不是调整大小(这就是我想要实现的)。
我还想在视觉上保持纵横比。
不确定我是否可以用纯CSS实现这一点,或者我需要使用fabricjs函数。
谢谢!
如果我理解正确,你想控制画布相对于div大小的大小,我认为我的代码可以帮助你解决你的问题:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body, html {
padding: 0;
margin: 0;
width: 100%;
height: 100%;
overflow: hidden;
}
#testBlock {
width: 300px;
background-color: yellow;
}
#myCanvas {
width: 600px;
}
</style>
</head>
<body>
<div id="testBlock">
<canvas id="myCanvas" width="600"></canvas>
</div>
<script src="fabric.min.js"></script>
<script>
var canvas = new fabric.Canvas('myCanvas', {
backgroundColor: "rgb(255, 0, 0)",
width: 150,
height: 150,
});
const observer = new ResizeObserver(entries => {
entries.forEach(entry => {
const { width, height } = entry.contentRect;
console.log(`Width: ${width}px, Height: ${height}px`);
// The height of the parent is not specified, so the height of the parent will be the same as that of canvas
canvas.setHeight(height);
canvas.setWidth(width / 2);
});
});
observer.observe(document.getElementById("testBlock"));
//document.getElementById('testBlock').setAttribute("style","width:900px");
//document.getElementById('testBlock').style.width = "900px";
</script>
</body>
</html>
如果您不想调整画布大小但想调整图像大小,请尝试缩放画布或缩放图像,我想您会在文档中找到正确的方法。