![](/img/trans.png)
[英]Maintaining object size and position for new fabric js objects like text,etc., (acoording to general canvas)
[英]Display objects in same position in different size canvas in fabric js
I am creating a canvas using fabric JS with a dynamic size in admin panel and adding objects into it, after modifying the canvas I am storing the JSON data into the database (using: canvas.toJSON()
). Now i have displayed a canvas in the front-end for editing using that stored JSON data from the database ( canvas.loadFromJSON(canvasData, this.canvas.renderAll.bind(this.canvas))
). 如果我使用与 canvas 相同的宽度和高度,它会完美显示。 但是,由于 canvas 的宽度和高度不同,对象不会显示在正确的 position 中,有时对象会被切碎。
For example, I have created a canvas with 1200*1000px
1000px in the admin now I want to load the canvas data into an 800*500px
canvas window with the objects in the same place. As if the original canvas is larger then I still have to fit the entire canvas data into the front-end so I need to load the canvas into a smaller canvas window.
var canvas = new fabric.Canvas('c', {width: 640, height: 360});
canvas.setDimensions({width: 1280, height: 720}, {backstoreOnly: true});
使用上述代码时,如果原始模板大小为3000*2000px
并适合600*600px
window 时,canvas 中的文本显示非常小,但从 ZFCC790C74C74CBDC1 正确生成图像时显示。 看图片
见图片我该如何解决这个问题? 提前致谢
这里有一些不同的尝试方法。
尝试这个
const scaleWidth = originalWidth / currentScreenWidth;
const scaleHeight = originalHeight / currentScreenHeight;
canvas.loadFromJSON(JSON.parse(myCanvasData),
canvas.renderAll.bind(canvas), (o, object) => {
object.scale(yourScaleValue);
});
object.scale 方法按比例缩放。
你也可以试试:
canvas.setWidth(originalWidth * canvas.getZoom());
canvas.setHeight(originalHeight * canvas.getZoom());
和...:
const scaleWidth = originalWidth / currentScreenWidth;
const scaleHeight = originalHeight / currentScreenHeight;
如果 scaleWidth 或 scaleHeight 小于 1,您将增加 canvas 和 object 大小。
如果 scaleWidth 或 scaleHeight 大于 1,您将减小 canvas 和 object 尺寸。
canvas.loadFromJSON(JSON.parse(myCanvasData),
canvas.renderAll.bind(canvas), (o, object) => {
if(scaleWidth > 1){
object.width = object.width / scaleWidth;
}else if (scaleWidth < 1){
const scalePercentage = 1 - scaleWidth;
object.width = (object.width * scalePercentage) + object.width;
}else{
//same size, no scaling necessary
}
});
最后:
canvas.viewportTransform = [(currentScreenWidth / originalWidth), 0, 0, (currentScreenHeight / originalHeight), 0, 0];
更改视口变换可能会产生负面影响。 例如:如果您正在加载的场景创建的宽度和高度为 1440 X 900,并且您当前的分辨率为 1920 X 1080,它将使用此代码正确加载,但在 go 向 canvas 添加新项目时将不同步。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.