怎么写html 和 Js 把本地图片上传到canvas里,实现旋转和画图,编辑后并保存下来
时间: 2024-05-21 07:14:00 浏览: 129
html和Js可以实现本地图片上传到canvas的操作,具体实现方式如下:
1.在HTML页面中添加一个用于上传文件的标签:
<input type="file" id="fileInput" />
2.JS代码中获取到上传的文件数据,并将其绘制到canvas上,代码如下:
var canvas = document.getElementById('canvasId');
var ctx = canvas.getContext('2d');
var fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', function () {
var file = fileInput.files[0];
var reader = new FileReader();
reader.onload = function (event) {
var img = new Image();
img.onload = function () {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
}
img.src = event.target.result;
}
reader.readAsDataURL(file);
})
3.实现拖拽功能,代码如下:
canvas.addEventListener('dragover', function (e) {
e.preventDefault();
});
canvas.addEventListener('drop', function (e) {
e.preventDefault();
var file = e.dataTransfer.files[0];
var reader = new FileReader();
reader.onload = function (event) {
var img = new Image();
img.onload = function () {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
}
img.src = event.target.result;
}
reader.readAsDataURL(file);
});
4.实现旋转和画图功能,代码如下:
var angle = 0;
document.getElementById('rotateBtn').addEventListener('click', function () {
angle += 90;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.translate(canvas.width / 2, canvas.height / 2);
ctx.rotate(Math.PI / 180 * angle);
ctx.drawImage(img, -img.width / 2, -img.height / 2);
ctx.restore();
});
document.getElementById('drawBtn').addEventListener('click', function () {
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(100, 100);
ctx.lineTo(150, 50);
ctx.closePath();
ctx.lineWidth = 2;
ctx.strokeStyle = 'red';
ctx.stroke();
});
5.实现保存功能,代码如下:
document.getElementById('saveBtn').addEventListener('click', function () {
var imgData = canvas.toDataURL("image/png");
var a = document.createElement('a');
a.href = imgData;
a.download = 'canvas.png';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
});
以上就是如何实现本地图片上传并在canvas中编辑保存的方法。
阅读全文