填充的种类 fill
<blockquote>
<p>官方介绍 <a href="http://fabricjs.com/fabric-intro-part-2#gradients" title="Introduction to Fabric.js. Part 2.">Introduction to Fabric.js. Part 2.</a></p>
</blockquote>
<h3>颜色填充 Color</h3>
<pre><code class="language-javascript">//投影
const fillColor = async function (text, options = {}) {
if (typeof text !== 'string' || text === '')
return null
const opt = {
top: 0, left: 0,
fill: '#000',
fontSize: 80,
fontFamily: '华文琥珀',
...options
}
new fabric.Text(text, opt)
}
</code></pre>
<h3>渐变色填充 Gradient</h3>
<pre><code class="language-javascript">
const fillGradient = function (text, options = {}) {
const opt = { ...options }
const oText = new fabric.Text(text, opt)
const height = oText.calcTextHeight()
const width = oText.calcTextWidth()
const gradient = new fabric.Gradient({
type: 'linear', // or 'radial'
gradientUnits: 'pixels', // or 'percentage'
coords: {
// r1: 0, r2: 0, // type: 'radial' only have
x1: opt.left, y1: 0,
x2: opt.left, y2: height
},
colorStops: [
{ offset: 0, color: 'rgb(254, 35, 93)' },
{ offset: 1, color: 'rgb(255, 199, 102)' }
]
})
oText.set('fill', gradient)
return oText
}
</code></pre>
<h3>图案填充 Pattern</h3>
<blockquote>
<p><a href="https://my.oschina.net/u/4297117/blog/4527555" title="js 完成对图片的等比例缩放的方法">js 完成对图片的等比例缩放的方法</a></p>
<p><a href="https://www.it1352.com/884313.html" title="使用fabric.js缩放画布时,像素完美缩放图像(Pixel perfect scaling of images while zooming the canvas with fabric.js)">使用fabric.js缩放画布时,像素完美缩放图像(Pixel perfect scaling of images while zooming the canvas with fabric.js)</a></p>
</blockquote>
<pre><code class="language-javascript">/** 返回Image对象 */
function asyncImage(src) {
console.log(src)
if (!src)
return null
return new Promise(resolve => {
const oImg = new Image()
// 解决跨域污染问题
oImg.crossOrigin = 'anonymous'
oImg.onerror = (res) => {
resolve(null);
console.error(res)
}
oImg.onload = () => {
resolve(oImg)
}
oImg.src = src
}
)
}
//图案填充
const asyncFillPattern = async function (text, options = {}) {
if (typeof text !== 'string' || text === '')
return null
const opt = {
top: 0, left: 0,
fill: '#000',
fontSize: 80,
fontFamily: '华文琥珀',
...options
}
const img = await asyncImage('data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAHklEQVQImWNkYGBgYGD4//8/A5wF5SBYyAr+//8PAPOCFO0Q2zq7AAAAAElFTkSuQmCC')
const pattern = new fabric.Pattern({
source: img, repeat: 'repeat'
})
return new fabric.Text(text, {
...opt,
fill: pattern
})
}
</code></pre>