当前位置:网站首页>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.setBackgroundImageSet the picture as the canvas background ; - stay
canvas.setBackgroundImageRefresh 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
fabricIt'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
边栏推荐
- Exercise notes 13 (effective letter ectopic words)
- Gee: find the spatial distribution and corresponding time of the "greenest" in the Yellow River Basin in 2020 [pixel by pixel analysis]
- Latest: the list of universities and disciplines for the second round of "double first-class" construction was announced
- Fabric.js 精简JSON
- Fabric.js 右键菜单
- Leetcode 18 problem [sum of four numbers] recursive solution
- Gee data set: export the distribution and installed capacity of hydropower stations in the country to CSV table
- Disable access to external entities in XML parsing
- Fabric.js 激活输入框
- Collectors. Groupingby sort
猜你喜欢

7.TCP的十一种状态集

Black Horse Notes - - set Series Collection

C case of communication between server and client based on mqttnet

LeetCode 1175. Prime number arrangement (prime number judgment + Combinatorial Mathematics)

LeetCode 241. 为运算表达式设计优先级(分治/记忆化递归/动态规划)

Fabric.js 精简JSON

Mathematical knowledge (Euler function)

黑馬筆記---Set系列集合

The El cascader echo only selects the questions that are not displayed

Preparation for writing SAP ui5 applications using typescript
随机推荐
C # picture display occupancy problem
C case of communication between server and client based on mqttnet
数据的储存
Video cover image setting, put cover images into multiple videos in the simplest way
Oracle和MySQL的基本区别(入门级)
Latest: the list of universities and disciplines for the second round of "double first-class" construction was announced
Find the subscript with and as the target from the array
Feign realizes file uploading and downloading
Fabric.js 更换图片的3种方法(包括更换分组内的图片,以及存在缓存的情况)
Dark horse notes -- Set Series Collection
Record my pytorch installation process and errors
LeetCode 241. 为运算表达式设计优先级(分治/记忆化递归/动态规划)
案例分享|智慧化的西部机场
Global and Chinese markets of semiconductor laser therapeutics 2022-2028: Research Report on technology, participants, trends, market size and share
js中的Map(含leetcode例题)
Fabric.js 基础笔刷
Splice characters in {{}}
函数中使用sizeof(arr) / sizeof(arr[0])求数组长度不正确的原因
Line by line explanation of yolox source code of anchor free series network (7) -- obj in head_ loss、Cls_ Loss and reg_ Calculation and reverse transmission of loss I
Fabric.js 背景不受视口变换影响