如何解决使 HTML Canvas 生成可用于 PDF 的线条艺术?
我有一个 HTML/JavaScript 程序,它使用 HTML5 画布生成漂亮的图形:
我想将此图表包含在我用 LaTeX 制作的书中。不幸的是,当我将此页面打印为 PDF 时,我得到了一个位图——大概是因为 canvas 是一个位图。
我刚刚检查了一下,显然如果我是用 SVG 而不是 HTML5 画布开发的,我会很高兴。但我没有。那么有什么方法可以从 HTML5 Canvas 生成线条艺术,还是我应该硬着头皮把它重新实现为 SVG?
(我使用 canvas 而不是 svg 因为我认为 Canvas 更受欢迎,更现代,更高效。我错了吗?)
编辑:这是我绘制每个箭头的 JavaScript。我相信我可以使用 svg.js
轻松地将其移植到 SVG /* Draw a Piece at its rotation at the position row,col */
drawRotatedPiece(p) {
let x = this.x(p.col);
let y = this.y(p.row);
this.ctx.beginPath();
this.ctx.save();
this.ctx.translate( x,y);
this.ctx.fillStyle='white';
this.ctx.fillRect( -this.radius,-this.radius,this.radius*2,this.radius*2 );
this.ctx.rotate( p.angle * Math.PI / 180);
this.ctx.moveto( 0,-this.radius );
this.ctx.lineto( -this.radius,0 );
this.ctx.lineto( +this.radius,0 );
this.ctx.closePath( );
this.ctx.fillStyle='black';
this.ctx.fill();
this.ctx.fillRect( -this.radius/2.0,this.radius,this.radius*2/3.0 );
this.ctx.restore();
}
解决方法
以下是生成 SVG 的代码,该代码可重现您在问题中给出的旋转片段。方法是drawRotatedPiece(x,y,radius,angle)
。
// Generate a SVG path command
function xycmd(cmd,x,y){
return cmd+ x + " " + y;
}
function rectpathxy(x,w,h){
return xycmd("M",y) +
xycmd("L",x+w,y+h) +
xycmd("L",y+h) +
"Z";
}
function drawRotatedPiece(x,angle){
trans=[];
svg="";
svg+="<path style='stroke:red;fill:white'";
svg+=" transform='translate("+x+","+y+")'";
svg+=" d='";
svg+=rectpathxy(-radius,-radius,radius*2,radius*2);
svg+="'/>";
svg+="<path style='stroke:none;fill:black'";
svg+=" transform='translate("+x+","+y+") rotate("+angle+")'";
svg+=" d='";
var w=radius;
var h=radius*2/3.0;
svg+= xycmd("M",-radius) +
xycmd("L",0) +
xycmd("L",+radius,0) +
"Z" +
xycmd("M",y) +
xycmd("L",y+h) +
xycmd("L",y+h) +
"Z";
svg+="'/>";
return svg;
}
如果您需要以 SVG 格式生成任何其他图形(尤其是像您这样的简单图形,只是一堆描边和填充路径),我在 Essentials of SVG 上的注释可以帮助您将这些图形转换为 SVG .
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。