之前写过下载二维码的需求,需求简单,只要能下载就行,但是下载到本地就一个纯二维码的小图片,感觉不怎么美观。
闲来无事,以下自己写了个小demo,丰富canvas下载到本地的图片内容,可以添加照片,描述文字,背景样式等…
准备两个节点
<canvas id="canvas"></canvas>
<a id="download" download href="">下载</a>
js实现绘制
const url = "https://t7.baidu.com/it/u=3766339589,272600460&fm=193&f=GIF";
const img = new Image(); // 创建img元素
const download = document.getElementById("download");
const imgFrame = new Image(); // 相框图片
imgFrame.setAttribute("crossorigin", "anonymous");
imgFrame.src = "https://img95.699pic.com/xsj/1c/xv/je.jpg!/fh/300";
img.setAttribute("crossorigin", "anonymous"); // 设置该属性 不然使用canvas.toDataURL会报错: Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
img.onload = function () {
const imgWidth = 600,
imgHeight = 500;
const canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
// 设置画布大小
canvas.width = imgWidth + 20;
canvas.height = imgHeight + 80;
// 绘制背景颜色
ctx.fillStyle = "pink";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 绘制文字(文本内容,x坐标,y坐标)
ctx.font = "28px serif";
ctx.fillStyle = "blue";
ctx.textAlign = "center";
ctx.fillText("点击图片或者下载按钮 下载图片到本地", canvas.width / 2, canvas.height - 10); // 中间位置开始绘制 配合 ctx.textAlign 使文字水平居中
ctx.strokeStyle = "red"; // 文本边框颜色
ctx.strokeText("点击图片或者下载按钮 下载图片到本地", canvas.width / 2, canvas.height - 10); // 文本边框
// 绘制图片(路径,x坐标,y坐标,x缩放大小,y缩放大小)
ctx.drawImage(imgFrame, 10, 10, imgWidth, imgHeight);
// 前 4 个是定义图像源的切片位置和大小,后 4 个则是定义切片的目标显示位置和大小
ctx.drawImage(img, 380, 100, 500, 380, 61, 65, 494, 380);
// 画线边框颜色
ctx.strokeStyle = "red";
ctx.beginPath();
ctx.moveTo(60, 65);
ctx.lineTo(560, 65);
ctx.lineTo(560, 450);
ctx.lineTo(60, 450);
ctx.lineTo(60, 65);
ctx.stroke();
download.href = canvas.toDataURL("image/png");
};
img.src = url; // 设置图片源地址
// 点击图片下载
canvas.onclick = function () {
download.click();
};
页面效果展示
下载到本地是包涵背景 + 图片 + 文字 的效果,可以实现页面中的图片,二维码等下载需求