使用Fabricjs填充拉伸图像的矩形 [英] Fill rectangle with stretched image with Fabricjs
本文介绍了使用Fabricjs填充拉伸图像的矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个使用Fabricjs绘制矩形的代码,并用图像模式和无重复填充矩形。以下是代码:
I have created a code for drawing a rectangle by using Fabricjs and fill the rectangle with an image pattern and with 'no-repeat'. Here is the code:
<!DOCTYPE HTML>
<html>
<head>
<script src="js/fabric.min.js" ></script>
</head>
<body>
<script>
function addRect() {
var canvas = new fabric.Canvas('c');
fabric.Object.prototype.transparentCorners = false;
canvas.setWidth(800);
canvas.setHeight(600);
function loadPattern(url) {
fabric.util.loadImage(url, function(img) {
rect.fill = new fabric.Pattern({
source: img,
repeat: 'no-repeat',
});
canvas.renderAll();
});
}
rect = new fabric.Rect({
left: 100,
top: 100,
width: 200,
height: 200,
angle: 0,
stroke: 'red',
strokeWidth: 3,
});
canvas.add(rect);
loadPattern('images/test.png');
document.getElementById('fillpattern').onchange = function() {
loadPattern('images/' + this.value+'.png');
};
canvas.renderAll();
}
</script>
<button onclick="addRect()">add</button>
<select id="fillpattern" name="fillpattern">
<option value="horizontal">horizontal</option>
<option value="vertical">vertical</option>
<option value="diagonal">diagonal</option>
<option value="cross">cross</option>
<option value="test">test</option>
</select>
<div>
<canvas id="c">
</canvas>
</div>
</body>
</html>
如何用拉伸图像填充矩形?
How could I fill the rectangle with a stretched image?
推荐答案
虽然在我的回答中我没有使用模式的概念,但我希望它能帮到你。
Although in my answer I am not using the concept of the pattern but I hope it will help you.
var canvas = new fabric.Canvas('c');
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.rect(40, 40, 220, 220);
ctx.closePath();
ctx.stroke();
ctx.clip();
var img = new Image();
img.onload = function () {
var img_ = new fabric.Image(img, {
left: 20,
top: 0,
height: 220,
width: 220,
selectable: true,
hasControls: false,
hasBorders: false
});
canvas.add(img_);
img_.sendToBack();
};
img.src = 'images/87357.jpg';
这篇关于使用Fabricjs填充拉伸图像的矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文