javascript:上传图像文件并将其绘制到画布中 [英] javascript: upload image file and draw it into a canvas
本文介绍了javascript:上传图像文件并将其绘制到画布中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在一个用于绘制图像的网络应用程序工作.我使用 CANVAS 元素和 javascript 来绘制它,但我有一个问题:如何从用户的 pc 加载图像并将其绘制在画布上?我不想保存在服务器上,只保存在网页上!
I work at a web application for painting images. I use a CANVAS element and javascript to draw on it, but I have a problem: how can I load an image from the pc of the user and draw it on the canvas? I don't want to save it on the server, only on the webpage!
这里是代码的缩短版本(完整代码会太长):
Here is a shortened version of the code (the full code would be too long):
HTML:
Open file: <input type="file" id="fileUpload" accept="image/*" /><br />
<canvas id="canvas" onmousemove="keepLine()" onmouseup="drawLine()" onmousedown="startLine()" width="900" height="600" style="background-color:#ffffff;cursor:default;">
Please open this website on a browser with javascript and html5 support.
</canvas>
javascript:
javascript:
var x = 0;
var y = 0;
var clicked = false;
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.strokeStyle = "black";
context.lineCap = "round";
canvas.addEventListener('mousemove', function(e) { getMousePos(canvas, e); }, false);
takePicture.onchange = function (event) {
var files = event.target.files,
file;
if (files && files.length > 0) {
file = files[0];
processImage(file);
}
};
function processImage(file) {
var reader = new FileReader();
reader.readAsDataUrl(file)
reader.onload = function(e) {
var img = new Image();
img.onload = function() {
context.drawImage(img, 100,100)
}
img.src = e.target.result;
}
}
// functions for drawing (works perfectly well)
function getMousePos(canvas, e) {
var rect = canvas.getBoundingClientRect();
x = evt.clientX - rect.left;
y = evt.clientY - rect.top;
}
function startLine() {
context.moveTo(x,y);
context.beginPath();
clicked = true;
}
function keepLine() {
if(clicked) {
context.lineTo(x,y);
context.stroke();
context.moveTo(x,y);
}
}
function drawLine() {
context.lineTo(x,y);
context.stroke();
clicked = false;
}
没有版权
推荐答案
const EL = (sel) => document.querySelector(sel);
const ctx = EL("#canvas").getContext("2d");
function readImage() {
if (!this.files || !this.files[0]) return;
const FR = new FileReader();
FR.addEventListener("load", (evt) => {
const img = new Image();
img.addEventListener("load", () => {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.drawImage(img, 0, 0);
});
img.src = evt.target.result;
});
FR.readAsDataURL(this.files[0]);
}
EL("#fileUpload").addEventListener("change", readImage);
canvas {display: block;}
<input type='file' id="fileUpload" />
<canvas id="canvas" width="300" height="200"></canvas>
这篇关于javascript:上传图像文件并将其绘制到画布中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文