爲圖片添加文字 canvas

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文檔</title>
</head>javascript

<body>
<canvas id='myCanvas' ></canvas>
<div id="imgCon" style="background: red"></div>
<script type="text/javascript">html


getImg('濟南店',8);
function getImg(text,fsz){
var img = new Image();
img.src = './timg.png';
img.onload=function(){//圖片加載完成,纔可處理
var c = document.getElementById("myCanvas");
c.width=img.width;
c.height=img.height;
var cxt = c.getContext("2d");
cxt.fillStyle = "rgba(255, 255, 255, 0)";
cxt.fillRect(0, 0, c.width, c.height);
cxt.drawImage(img,0,0);
cxt.save();
cxt.font = fsz+"px Arial";
cxt.textBaseline = 'middle';//更改字號後,必須重置對齊方式,不然居中麻煩。設置文本的垂直對齊方式
cxt.textAlign = 'center';
var tw = cxt.measureText(text).width;
var ftop = c.height/2-5;
var fleft = c.width/2;
//cxt.fillStyle="#ff0000";
//cxt.fillRect(fleft-tw/2,ftop-fsz/2,tw,fsz);//矩形在畫布居中方式
//cxt.fillStyle="#ffffff";
cxt.fillText(text,fleft,ftop);//文本元素在畫布居中方式
cxt.strokeStyle = 'white';
cxt.strokeText(text,fleft,ftop);//文字邊框java

var ii=(new Image())
ii.src=c.toDataURL('image/jpeg')
document.getElementById("imgCon").appendChild(ii)canvas


};
app

}異步

 

/*getBase64('./timg1.png')
function getBase64(url){
//經過構造函數來建立的 img 實例,在賦予 src 值後就會馬上下載圖片,相比 createElement() 建立 <img> 省去了 append(),也就避免了文檔冗餘和污染
var Img = new Image(),
dataURL='';
Img.src=url;

Img.onload=function(){ //要先確保圖片完整獲取到,這是個異步事件
var canvas = document.createElement("canvas"), //建立canvas元素
width=Img.width, //確保canvas的尺寸和圖片同樣
height=Img.height;
canvas.width=width;
canvas.height=height;
canvas.getContext("2d").drawImage(Img,0,0,width,height); //將圖片繪製到canvas中函數


dataURL=canvas.toDataURL('image/jpeg'); //轉換圖片爲dataURL
console.log(dataURL)
};
}*/ui

</script></body></html>url

相關文章
相關標籤/搜索