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