当前位置:网站首页>Fabric. JS upload local image to canvas background
Fabric. JS upload local image to canvas background
2022-07-02 05:17:00 【Director of Moral Education Department】
In this paper,
I use Fabric.js
The version is 4.6.0
.
The effect to be achieved this time is : Upload a picture locally , Then render to canvas
in ( As a background ).
I will use Native The method is implemented once , And then in Vue3 + Element-plus
Realize once in the environment .
Talk about my last practice in the project .
<br>
demand :
- Upload pictures by clicking the upload button
- Get the picture , Put it on the canvas and render
It should be noted that , This paper mainly realizes Upload the picture and render it to the canvas The logic of , Therefore, there is no restriction on the type of uploaded files , There is no file size limit . If you need to limit file types in your business , Just add the method of restriction on the basis of this case .
<br>
All the codes in this article are in the warehouse given at the end of the article .
If the content of this article is helpful to you , Please also give me a compliment ~
<br><br>
Native operation
adopt <input type="file" />
Get image path , Will be affected by browser security policy , So we need to deal with .
Implementation logic :
- Well defined Upload button and canvas (HTML part );
- Initialize canvas ;
- Click the upload button Get image address ( Here we need to deal with the problem of security policy );
- Get the picture path , Use
canvas.setBackgroundImage
Set the picture as the canvas background ; - stay
canvas.setBackgroundImage
Refresh the canvas in the callback function of ;
<br>
<div> <input type="file" name="file" id="upload" onchange="handleUpload()" /> <button onclick="saveCanvas()"> preservation </button></div><canvas id="canvas" width="600" height="600" style="border: 1px solid #ccc;"></canvas><!-- introduce fabric.js --><script src="https://cdn.bootcdn.net/ajax/libs/fabric.js/460/fabric.js"></script><script>// Of uploaded files DOM Elements const uploadEl = document.getElementById("upload")// canvas let canvas = null// Initialize canvas function initCanvas() { canvas = new fabric.Canvas('canvas')}// Upload file event function handleUpload() { // Upload the first file in the file list const file = uploadEl.files[0] // Address of picture file let imgPath = null // Get the real path of the picture file // Due to browser security policy , Now you need to do this // This code is copied from the Internet , If you want to have an in-depth understanding, you can baidu search “C:\fakepath\” if (window.createObjcectURL != undefined) { imgPath = window.createOjcectURL(file); } else if (window.URL != undefined) { imgPath = window.URL.createObjectURL(file); } else if (window.webkitURL != undefined) { imgPath = window.webkitURL.createObjectURL(file); } // Set canvas background , And refresh the canvas canvas.setBackgroundImage( imgPath, canvas.renderAll.bind(canvas) )}// Save the canvas function saveCanvas() { let data = canvas.toJSON() console.log(data)}window.onload = function() { initCanvas()}</script>
The above implementation , If it is in a pure front-end environment , When saving, the background image is the local address ( "blob:http://127.0.0.1:5500/383e7860-3fa5-43b9-92d9-e7165760e60b"
).
This is actually not very good , If you want to pass on another computer Deserialization When rendered , There may be a problem .
<br>
If the way of pure front-end implementation , You can turn the picture into base64
Then generate the background image .
fabric.Image.fromURL( imgPath, // Real picture address img => { // Set the picture on the canvas , Then re render the canvas , The picture comes out . canvas.setBackgroundImage( img, // Picture to set canvas.renderAll.bind(canvas) // Re render the canvas ) })
<br><br>
stay element-plus Operation in
I use the vue3 + element-plus
.
The implementation logic is the same as the native method . The only difference is that this example uses el-upload
This component . I convert the picture file into base64
Then put it on the canvas .
<template> <div> <div class="btn__x"> <!-- Upload components --> <el-upload action="https://jsonplaceholder.typicode.com/posts/" :multiple="false" :show-file-list="false" :limit="1" accept=".jpg,.png" :before-upload="onProgress" > <el-button type="primary"> Upload </el-button> </el-upload> <!-- Save button ( serialize ) --> <el-button @click="saveCanvas"> preservation : Open the console to see </el-button> </div> <!-- canvas --> <canvas id="canvas" width="600" height="600" style="border: 1px solid #ccc;"></canvas> </div></template><script setup>import { onMounted, ref } from 'vue'import { useStore } from 'vuex'import { fabric } from 'fabric'const store = useStore()// canvas let canvas = null// Upload function onProgress(file) { // Take the picture file const reader = new FileReader() reader.readAsDataURL(file) // After the picture file is completely obtained, execute reader.onload = () => { // convert to base64 Format const base64Img = reader.result // take base64 Set the picture as the background canvas.setBackgroundImage( base64Img, canvas.renderAll.bind(canvas) // Refresh the canvas ) } return false}// Initialize canvas function init() { canvas = new fabric.Canvas('canvas')}// preservation function saveCanvas() { console.log(canvas.toJSON())}// After the page loads , Initialize canvas onMounted(() => { init()})</script><style lang="scss" scoped>.btn__x { display: flex; .el-button { margin-right: 20px; }}</style>
<br><br>
In formal development
In formal project development , The probability of the above two situations should not be much ( Unless your back-end partner is a lazy person )
Let's talk about the problems in the above two situations first :
- The picture path is the local address , Saving to the server is meaningless .
- Turn into base64 To preserve , Fields can be large .
<br>
In this case, it may not be useful to put it on the server . 127.0.0.1
It's yours , The pictures you upload may not be viewable on other people's computers .
<br>
Although this situation is not a big problem , but backgroundImage.src
The value of is a little big .
<br>
What I do in the project :
- The front end uploads pictures to the back end
- The back end saves the picture to the server , Then return a picture url To the front end
- The front end gets the picture url, Then put it in
fabric
It's in the background
The advantage of this is backgroundImage.src
The value of becomes shorter .
<br>
In a formal project , The size of the canvas must be taken into account . You can refer to 《Fabric.js From entry to expansion 》 in “ Stretch background ” This section .
<br><br>
Code warehouse
stay Vue3+Element-plus To realize
<br><br>
Recommended reading
《Fabric.js From entry to expansion 》 <br> 《Fabric.js Gradient effect ( Including radial gradient )》 <br> 《Fabric.js 3 individual api Set canvas width and height 》 <br> 《Fabric.js Customize the right-click menu 》 <br> 《Fabric.js Change the picture 3 Methods ( Including changing pictures in the Group , And the existence of cache )》 <br>
If the content of this article is helpful to you , Please also give me a compliment ~ give the thumbs-up + Focus on + Collection = Learned to
边栏推荐
- el form 表单validate成功后没有执行逻辑
- LS1046nfs挂载文件系统
- A new attribute value must be added to the entity entity class in the code, but there is no corresponding column in the database table
- Mathematical knowledge (Euler function)
- Pyechart1.19 national air quality exhibition
- 6. Network - Foundation
- 7.1 Résumé du concours de simulation
- Global and Chinese market of hydrocyclone desander 2022-2028: Research Report on technology, participants, trends, market size and share
- Storage of data
- [high speed bus] Introduction to jesd204b
猜你喜欢
Express logistics quick query method, set the unsigned doc No. to refresh and query automatically
Fabric.js 激活输入框
About PROFIBUS: communication backbone network of production plant
Mathematical problems (number theory) trial division to judge prime numbers, decompose prime factors, and screen prime numbers
Here comes the chicken soup! Keep this quick guide for data analysts
Gee dataset: chirps pentad high resolution global grid rainfall dataset
Summary of database problems
黑馬筆記---Set系列集合
Differential identities (help find mean, variance, and other moments)
C# 基于MQTTNet的服务端与客户端通信案例
随机推荐
國產全中文-自動化測試軟件Apifox
Johnson–Lindenstrauss Lemma(2)
The reason why sizeof (ARR) / sizeof (arr[0]) is used in the function to calculate the length of the array is incorrect
Online English teaching app open source platform (customized)
Domestic all Chinese automatic test software apifox
设置滚动条默认样式 谷歌浏览器
Implementation of go language for deleting duplicate items in sorting array
Fabric.js 右键菜单
Go GC garbage collection notes (three color mark)
Global and Chinese market of hydrocyclone desander 2022-2028: Research Report on technology, participants, trends, market size and share
Summary of database problems
go实现leetcode旋转数组
el-cascader回显只选中不显示的问题
Fabric.js 渐变
C case of communication between server and client based on mqttnet
Fabric.js IText 上标和下标
将光盘中的cda保存到电脑中
Find the subscript with and as the target from the array
Creation and destruction of function stack frames
Leetcode 18 problem [sum of four numbers] recursive solution