[英]Resize background image of canvas - Fabricjs
我正在使用 fabricjs 來玩畫布,並通過 javascript 將圖像加載到其中。
我有一個功能可以調整畫布大小以使其具有響應性,因此我想調整加載的背景圖像的大小以適合畫布但保持縱橫比。
我目前還沒有找到符合我標准的例子,希望有人能提供幫助。
Javascript
var canvas = new fabric.Canvas('drawing_layer');
var img = new Image();
img.onload = function () {
canvas.setBackgroundImage(img.src, canvas.renderAll.bind(canvas), {
originX: 'left',
originY: 'top',
left: 0,
top: 0
});
// initially sets width of canvas to fit the image
canvas.setDimensions({
width: img.width,
height: img.height
});
};
// below is a call to function that resizes the canvas
resizeCanvas();
//sets listener to resize event
window.addEventListener('resize', resizeCanvas);
您的 resizeCanvas() 應如下所示:
resizeCanvas(width, height) {
canvas.backgroundImage.scaleToWidth(width);
canvas.backgroundImage.scaleToHeight(height);
canvas.setDimensions({width: width, height: height});
canvas.renderAll();
}
你應該沒問題。
我在 Angular 2+ 中的解決方案。
@HostListener('window:resize', ['$event'])
resizeCanvas(event?: any) {
const width: number = (window.innerWidth > 0) ? window.innerWidth : screen.width;
const height: number = (window.innerHeight > 0) ? window.innerHeight : screen.height;
const widthn: number = width * 0.7;
const heightn: number = height - 100;
canvas.setDimensions({
width: widthn,
height: heightn,
});
}
為了通過保留圖像的縱橫比來設置背景圖像,並將其設置在畫布的中心。
const setBackgroundFromDataUrl = (dataUrl, options = {}) => {
if (!dataUrl) { return true; }
let img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.onload = () => {
// maxWidth // Max width of the canvas
// maxHeight //Max height of canvas
let imgWidth = img.width; // Current image width
let imgHeight = img.height; // Current image height
let widthAspectRatio = maxWidth / imgWidth;
let heightAspectRatio = maxHeight / imgHeight;
let finalAspectRatio = Math.min(widthAspectRatio, heightAspectRatio)
let finalHeight = imgHeight * finalAspectRatio;
let finalWidth = imgWidth * finalAspectRatio;
let imgTop = 0;
if (maxHeight > finalHeight) {
imgTop = (Math.round(maxHeight) - Math.round(finalHeight)) / 2;
}
let imgLeft = 0;
if (maxWidth > finalWidth) {
imgLeft = (Math.round(maxWidth) - Math.round(finalWidth)) / 2;
}
let nsgImage = new fabric.Image(img).scale(finalAspectRatio);
nsgImage.set({ left: imgLeft, top: imgTop });
canvas.setBackgroundImage(nsgImage, () => canvas.renderAll());
}
img.src = dataUrl;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.