[英]Is there a way to modify an Image with Javascript?
所以我有一个项目,用户可以根据他们的输入生成 pdf。 使用jspdf
库生成 PDF 文件。 问题是,用户可以上传个人资料图片,我想以圆角或完全圆角( border-radius
为 50%)显示该图像。 由于没有本地 function 允许在jspdf
或据我所知的任何其他库( pfdkit
, pdfmake
)中进行此操作,因此我正在寻找一种在生成pdf
之前修改图像的方法。
我已经尝试过使用html2canvas
,实际上效果很好。 当用户在他们的移动设备上时,会出现html2canvas
的问题。 由于图像的width
和height
调整为屏幕尺寸(两者都在35px
左右),使用html2canvas
拍摄快照,然后在宽度和高度为 100px 的 pdf 中显示,图像显然变得模糊.
所以理想情况下,在使用jspdf
生成 PDF 文件之前,我需要一些东西来编辑原始图像或其他东西。
任何其他让我更接近解决方案的想法也非常感谢。
只是为了澄清,简单地向图像添加 CSS 属性将无济于事。 jspdf
仅使用img
标签中的图像,没有任何 css 属性。
我建议您在生成 pdf 之前将 class 添加到图像中,并在 ZC7A628CBA2AEE28EB661
.circle {
border-radius: 50%;
}
或者,如果已经有 css 与 img 标签的一些边界半径值,即使您也可能需要强制:
.circle {
border-radius: 50% !important;
}
可以在 jspdf 上使用圆角图像,如果您已经调整大小,则只需在将图像添加到 PDF 之前对图像应用圆角。
roundedImage
取自: Canvas 圆角drawimage
例如(不能在 SO 上工作,所以没有演示):
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="UTF-8" />
<script src="https://unpkg.com/jspdf@latest/dist/jspdf.min.js"></script>
<style>
* {
margin: 0;
padding: 0;
}
body {
background: #ccc;
}
#pdf {
display: block;
position: absolute;
bottom: 0;
width: 100vw;
height: 100vh;
}
</style>
</head>
<body>
<embed id="pdf" src="#" type="application/pdf" width="100%" height="100%" />
<script>
function roundedImage(ctx, x, y, width, height, radius) {
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(
x + width,
y + height,
x + width - radius,
y + height
);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
}
var img = new Image();
img.src = "https://graph.facebook.com/649650002/picture?type=square";
img.setAttribute("crossorigin", "anonymous");
img.onload = function() {
//
const canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext("2d");
roundedImage(ctx, 0, 0, 50, 50, 5);
ctx.clip();
ctx.drawImage(img, 0, 0, img.width, img.height);
ctx.restore();
// Default export is a4 paper, portrait, using milimeters for units
var doc = new jsPDF();
doc.text("woop!..rounded corners.", 10, 15);
doc.addImage(canvas.toDataURL("image/png"), "PNG", 15, 25, 30, 30);
document.getElementById("pdf").src = doc.output(
"dataurlstring",
"its-a.pdf"
);
};
</script>
</body>
</html>
如果有人出于某种原因偶然发现了这篇文章,我实际上已经达到了我想要的结果。 正如我所说,用户能够上传图像,我想用圆角或 50% 的边框半径显示该图像。 无论如何,在预览(和上传)图像到我的网站之前,用户必须使用cropperjs
裁剪图像。 然后,他们可以自行决定是否要显示具有圆角或边框半径为 50% 的图像。 我认为这极大地促进了用户体验和我的最终结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.