簡體   English   中英

在織物js中以不同尺寸canvas在相同的position中顯示對象

[英]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.

在fabric js中關注了Canvas客戶端大小

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM