当前位置:网站首页>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
边栏推荐
- Collectors.groupingBy 排序
- 数据的储存
- [common error] the DDR type of FPGA device is selected incorrectly
- Gee series: unit 6 building various remote sensing indexes in Google Earth engine
- Fabric.js 更换图片的3种方法(包括更换分组内的图片,以及存在缓存的情况)
- 国产全中文-自动化测试软件Apifox
- Global and Chinese market of pressure gauges 2022-2028: Research Report on technology, participants, trends, market size and share
- Feign realizes file uploading and downloading
- Fabric.js IText设置指定文字的颜色和背景色
- Gee: create a new feature and set corresponding attributes
猜你喜欢

Here comes the chicken soup! Keep this quick guide for data analysts
![[opencv] image binarization](/img/7e/b56a59ffae3bf6cac9c0bb7e090b85.jpg)
[opencv] image binarization

Gee series: unit 6 building various remote sensing indexes in Google Earth engine

Fabric.js IText 上标和下标

Simple and practical accounting software, so that accounts can be checked

Mysql基础---查询(1天学会mysql基础)

黑马笔记---Map集合体系

指针使用详解

Cubemx DMA notes

Preparation for writing SAP ui5 applications using typescript
随机推荐
Global and Chinese market of insulin pens 2022-2028: Research Report on technology, participants, trends, market size and share
Collectors.groupingBy 排序
Gee series: Unit 2 explore datasets
leetcode两数相加go实现
LeetCode 241. 为运算表达式设计优先级(分治/记忆化递归/动态规划)
[opencv] image binarization
How to make an RPM file
C # picture display occupancy problem
Find the subscript with and as the target from the array
Online English teaching app open source platform (customized)
运维工作的“本手、妙手、俗手”
Implementation of go language for deleting duplicate items in sorting array
Gee series: unit 7 remote sensing image classification using GEE [random forest classification]
Leetcode basic programming: array
Pycharm breakpoint management: temporarily cancel some breakpoints + run directly to a line
el form 表单validate成功后没有执行逻辑
No logic is executed after the El form is validated successfully
Gee: remote sensing image composite and mosaic
Gee series: unit 8 time series analysis in Google Earth engine [time series]
2022 Alibaba global mathematics competition, question 4, huhushengwei (blind box problem, truck problem) solution ideas