当前位置:网站首页>Fabric. JS three methods of changing pictures (including changing pictures in the group and caching)
Fabric. JS three methods of changing pictures (including changing pictures in the group and caching)
2022-07-02 05:17:00 【Director of Moral Education Department】
Brief introduction
I list. 3 Plant in Fabric.js in Change pictures Methods .
It also includes Replace the pictures in the group The operation of .
<br>
<br>
Environment and version
Chrome Browser version :96.0.4664.45
Fabric.js edition :4.6.0
I developed it in a native environment , It also provides a copy of Vue3 Code developed in the environment ( There is a link at the end of the article ).
<br>
<br>
Hands-On Activities
Next there is 3 A case , Used 2 A picture Agumon.png and Bhikkhu.png, The picture is in iconfont Found on the website .
If you need to use the picture of this case , It can be obtained in the warehouse provided at the end of the text .
scene 1: Change the of picture elements src
If you add... To the canvas Image object , Then you can use Image.setSrc Set new picture , And then use Canvas.renderAll Refresh the canvas .

<style> canvas { border: 1px solid #ccc; }</style><button onclick="change()"> Modify picture </button><canvas width="300" height="300" id="canvas"></canvas><script src="https://cdn.bootcdn.net/ajax/libs/fabric.js/460/fabric.min.js"></script><script> // Instantiation canvas canvas = new fabric.Canvas('canvas') // Create a picture object fabric.Image.fromURL('../../images/Agumon.png', oImg => { // Add picture objects to canvas in canvas.add(oImg) }) // Change picture event function change() { // Get the picture object . Because in this case , There is only one element in the canvas , use getObjects() The first element of the obtained array is the image const img = canvas.getObjects()[0] // Use setSrc Method to change the picture , The second parameter is the callback function , Refresh in the callback function canvas that will do img.setSrc('../../images/Bhikkhu.png', () => { canvas.renderAll() }) }</script>The above scenario is the simplest .
If there are multiple figures and pictures on the canvas , You may need to add some custom attributes when creating images .
Use fabric.getObjects().find() Just search .
find() Is the original method of array .
<br>
<br>
scene 2: Modify the pictures in the group ( No cache )
Creating groups is cached by default , If there is a cache, use Canvas.renderAll() Method does not update the image .
So when you create a group, you should declare Don't cache : Group.objectCaching.

<style> canvas { border: 1px solid #ccc; }</style><button onclick="change()"> Modify picture </button><canvas width="300" height="300" id="canvas"></canvas><script src="https://cdn.bootcdn.net/ajax/libs/fabric.js/460/fabric.min.js"></script><script> // Instantiation canvas canvas = new fabric.Canvas('canvas') // Create a picture object fabric.Image.fromURL('../../images/Agumon.png', oImg => { // Text const text = new fabric.Text(' Groups without cache ', { fontSize: 14, top: 50 }) // Create group const group = new fabric.Group([oImg, text], { objectCaching: false // Don't cache !!! }) // Add group to canvas in canvas.add(group) }) // Change picture event function change() { // Get group const group = canvas.getObjects()[0] // Get photo const img = group.getObjects().find(item => { // adopt isType Judge picture elements , Because there are 2 Elements ( A picture , A text ) return item.isType('image') }) // Find pictures , Then replace img.setSrc('../../images/Bhikkhu.png', () => { // After changing the picture , refresh canvas canvas.renderAll() }) }</script> This kind of situation , Focus on creating groups , To declare objectCaching: false.
<br>
<br>
scene 3: Modify the pictures in the group ( With cache )
If Group (Group) Set cache , It needs to be replaced again Group (Group) Pictures in .
Here's what I did :
- Look for picture objects , And save it to a variable ;
- Delete picture objects in the group ( Use
Group.removeWithUpdate); - Update the of the picture object
srcPoint to ( UseImage.setSrc); - Put the pictures into groups ( Use
Group.addWithUpdate); - Re render the canvas ( Use
Canvas.renderAll);
<br>

<style> canvas { border: 1px solid #ccc; }</style><button onclick="change()"> Modify picture </button><canvas width="300" height="300" id="canvas"></canvas><script src="https://cdn.bootcdn.net/ajax/libs/fabric.js/460/fabric.min.js"></script><script> // Instantiation canvas canvas = new fabric.Canvas('canvas') // Create a picture object fabric.Image.fromURL('../../images/Agumon.png', oImg => { // Text const text = new fabric.Text(' Groups without cache ', { fontSize: 14, top: 50 }) // Create group const group = new fabric.Group([oImg, text]) // Add group to canvas in canvas.add(group) }) // Change picture event function change() { // Get group const group = canvas.getObjects()[0] // 【1】 Look for picture objects , And save it to a variable const img = group.getObjects().find(item => { // adopt isType Judge picture elements , Because there are 2 Elements ( A picture , A text ) return item.isType('image') }) // 【2】 Delete picture objects in the group group.removeWithUpdate(img) // 【3】 Update the of the picture object `src` Point to img.setSrc('../../images/Bhikkhu.png', () => { // 【4】 Put the pictures into groups group.addWithUpdate(img) // 【5】 Re render the canvas canvas.renderAll() }) }</script>According to this example, the goal can be achieved , But I always feel uncomfortable .
If you have better ideas to share , Discuss learning together .
<br>
If you also need to change the picture in your project , But not above 3 In two scenarios , You can leave a message , I'll try to solve .
<br>
<br>
Code warehouse
Native way to achieve Change picture
stay Vue3 Use in Fabric Realization Change picture
<br>
<br>
More recommendations
《Fabric.js From entry to mastery 》
《Fabric.js Achieve gradient (Gradient) effect , Including radial gradient radial》
《Fabric.js Customize the right-click menu 》
give the thumbs-up + Focus on + Collection = Learned to
边栏推荐
- Database batch insert data
- Global and Chinese market of pressure gauges 2022-2028: Research Report on technology, participants, trends, market size and share
- 7.1模擬賽總結
- Fabric.js 基础笔刷
- No logic is executed after the El form is validated successfully
- How matlab marks' a 'in the figure and how matlab marks points and solid points in the figure
- Mathematical knowledge (Euler function)
- 操作符详解
- Disable access to external entities in XML parsing
- LeetCode 1175. 质数排列(质数判断+组合数学)
猜你喜欢
![[bus interface] Axi interface](/img/ee/95ade7811ec2c37fb67a77f0b6ae2a.jpg)
[bus interface] Axi interface
![Gee series: unit 7 remote sensing image classification using GEE [random forest classification]](/img/01/ba9441b7b1efaed85c464316740edb.jpg)
Gee series: unit 7 remote sensing image classification using GEE [random forest classification]

Gee: create a new feature and set corresponding attributes

黑马笔记---Set系列集合

6. Network - Foundation

Here comes the chicken soup! Keep this quick guide for data analysts

Mathematical problems (number theory) trial division to judge prime numbers, decompose prime factors, and screen prime numbers
![Gee series: unit 9 generate sampling data in GEE [random sampling]](/img/ff/edb27b40f63eca81c5683e81b2860b.jpg)
Gee series: unit 9 generate sampling data in GEE [random sampling]

Paddlepaddle project source code

2022 Alibaba global mathematics competition, question 4, huhushengwei (blind box problem, truck problem) solution ideas
随机推荐
指针使用详解
No logic is executed after the El form is validated successfully
国产全中文-自动化测试软件Apifox
Video cover image setting, put cover images into multiple videos in the simplest way
The underlying principle of go map (storage and capacity expansion)
LeetCode 1175. Prime number arrangement (prime number judgment + Combinatorial Mathematics)
Pyechats 1.19 generate a web version of Baidu map
7.TCP的十一种状态集
数据库批量插入数据
Gee series: Unit 4 data import and export in Google Earth engine
Gee: use of common mask functions in remote sensing image processing [updatemask]
Global and Chinese market of insulin pens 2022-2028: Research Report on technology, participants, trends, market size and share
在{{}}中拼接字符
2022 Alibaba global mathematics competition, question 4, huhushengwei (blind box problem, truck problem) solution ideas
LeetCode 1175. 质数排列(质数判断+组合数学)
Two implementation methods of delay queue
Mathematical knowledge -- understanding and examples of fast power
Gee series: unit 8 time series analysis in Google Earth engine [time series]
7.1模擬賽總結
Online English teaching app open source platform (customized)