2014-12-18 127 views
0

我正在構建一個需要將文本轉換爲圖像,保留格式的chrome擴展。看起來像這樣使用window.getSelection的結果是可能的,但它也會對編程所有的邊緣情況有點難以理解。一直在網上尋找現有的解決方案,但沒有看到過 - 是否有人知道這種技術的存在?將文本轉換爲畫布圖像,保留格式

如果沒有,我會後我的工作github上時,它的進一步沿着:)

乾杯,

艾倫

回答

1

畫布本身可以直接繪製簡單地格式化文本。

enter image description here

這些性質可以被用於影響文本如何繪製在畫布上

  • 字體:大小& fontface

  • textAlign設置(水平對齊) :開始,結束,左側,右側,中心

  • textBaseline(垂直取向):字母,頂部,掛,中,表意,底部

  • 的StrokeStyle(顏色勾勒出的字形):RGBA,六角,webcolor名,梯度

  • 的FillStyle(顏色填充的字形):RGBA,六角,webcolor名,梯度

  • 不透明度:設置爲0.00(完全透明)至1.00(完全不透明)刻度

  • lineWidth(粗划行程的厚度):0。50+

  • 變換(刻度&旋轉文本)

  • 剪切:文本可以由下式定義的路徑

  • 合成(文本和其他附圖的相互作用)被裁剪:

而你c一個使用context.measureText使用獲得的文本

可以在畫布上繪製文本轉換爲圖像的寬度canvasElement.toDataURL

var canvas=document.getElementById("canvas"); 
 
var ctx=canvas.getContext("2d"); 
 
var cw=canvas.width; 
 
var ch=canvas.height; 
 

 
ctx.font='60px verdana'; 
 
ctx.textAlign='center'; 
 
ctx.textBaseline='middle'; 
 
ctx.strokeStyle='black'; 
 
ctx.fillStyle='green'; 
 
ctx.lineWidth=2; 
 

 
ctx.translate(100,50); 
 
ctx.rotate(-Math.PI/16); 
 
ctx.fillText("Earth",0,0); 
 
ctx.strokeText("Earth",0,0); 
 
ctx.setTransform(1,0,0,1,0,0); 
 

 
ctx.translate(275,50); 
 
ctx.rotate(Math.PI/16); 
 
ctx.fillText("quake",0,0); 
 
ctx.strokeText("quake",0,0); 
 
ctx.setTransform(1,0,0,1,0,0); 
 

 
var textAsImage=new Image(); 
 
textAsImage.onload=function(){ 
 
    document.body.appendChild(textAsImage); 
 
} 
 
textAsImage.src=canvas.toDataURL();
body{ background-color:white; padding:10px; } 
 
#canvas{border:1px solid red;}
<p>Simple text drawn on a canvas element</p> 
 
<canvas id="canvas" width=400 height=150></canvas> 
 
<p>The canvas converted to an image</p>