有没有办法让Fabric.js画布使用浏览器调整大小以在任何设备上启用相同的结果?我在谈论响应式设计。
有没有代码示例?
答案 0 :(得分:8)
此jsFiddle是可行的解决方案。它受此github issue的启发。
这些是必需的东西:
围绕由布料控制的画布的div。
//Switch on/off function
handleChange = (event, id) => {
const isChecked = event;
this.setState(
({switch_status}) => ({
switch_status: {
...switch_status,
[id]: isChecked,
}
})
);
}
//Loop Items
this.state.items.map((item, index) => (
<Switch
className="custom-switch custom-switch-primary"
checked={this.state.switch_status[index]}
id={index}
onChange={event => handleChange(event, index)}
/>
))
还有一个窗口调整大小处理程序,可触发新画布尺寸和缩放的计算和设置。
<div class="fabric-canvas-wrapper">
<canvas id="theCanvas"></canvas>
</div>
仅此而已。它似乎工作正常。请让我知道此解决方案是否有任何问题。
我在3.6.2。版本中使用了fabric.js。
答案 1 :(得分:7)
基本上你需要获得设备屏幕的宽度和高度。然后在Javascript中相应地调整画布大小。例如:
var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
var height = (window.innerHeight > 0) ? window.innerHeight : screen.height;
var canvas = document.getElementById("canvas");
canvas.width = width;
canvas.height = height;
您可能拥有不同分辨率的屏幕,在这种情况下我通常会计算您的原始宽度和设备的宽度比,然后相应地使用该值调整宽度和高度。例如:
var originalWidth = 960; //Example value
var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
var widthRatio = originalWidth / width;
canvas.width *= widthRatio;
canvas.height *= widthRatio;
这通常适用于任何设备,希望这会有所帮助。
答案 2 :(得分:3)
我知道已经有一段时间了,但我发现使用缩放功能更简单的方法。
完成窗口调整大小后会触发此代码。它允许我根据新维度确定调整画布中所有内容所需的缩放系数。
function rescale_canvas_if_needed()
{
var optimal_dimensions = get_optimal_canvas_dimensions();
var scaleFactor=optimal_dimensions[0]/wpd.canvas_w;
if(scaleFactor != 1) {
wpd_editor.canvas.setWidth(optimal_dimensions[0]);
wpd_editor.canvas.setHeight(optimal_dimensions[1]);
wpd_editor.canvas.setZoom(scaleFactor);
wpd_editor.canvas.calcOffset();
wpd_editor.canvas.renderAll();
}
}
$( window ).resize(function() {
clearTimeout(resizeId);
resizeId = setTimeout(handle_resize, 500);
});
function handle_resize()
{
$(".canvas-container").hide();
rescale_canvas_if_needed();
$(".canvas-container").show();
}
答案 3 :(得分:1)
我认为这是我需要的答案https://stackoverflow.com/a/29445765/1815624
它看起来是如此接近,但是经过一些调整后,我得到了想要的东西,并在需要时将其缩小,并以1的比例最大化。
所需的画布大小应设置为宽度/高度awk '{$1 = $1; print}' file1 > file2
这也需要更多更改以处理高度,因此当用户在那儿旋转手机以使其横向移动时,在屏幕上看到全部内容可能变得很大 此示例的新编辑代码的宽度和高度将为1000像素
更新:添加了对高度和宽度的检测以缩放到窗口...
var optimal_dimensions = [1000,1000];
希望这对某人有帮助...美好的一天。
答案 4 :(得分:0)
使用jQuery根据元素的大小调整画布的大小。
window.addEventListener('resize', resizeCanvas, false);
function resizeCanvas() {
canvas.setHeight(jQuery('#image').height());
canvas.setWidth(jQuery('#image').width());
canvas.renderAll();
}
resizeCanvas();