喂,你是誰啊?
DEMO 原始碼文章末尾
HTML結構
<div class="container">
<div class="container-wrap">
<canvas id="canvas" width="250" height="250"></canvas>
<!-- Control -->
<section class="control">
<select id="control-select">
<option value="立花瀧">立花瀧</option>
<option value="宮水三葉">宮水三葉</option>
</select>
<input type="text" placeholder="要寫的字" id="control-name" maxlength="3"/>
<button id="control-create">生成圖片</button>
<p class="control-result"></p>
</section>
</div>
</div>
複製程式碼
頁面互動
獲取相關的DOM元素
const DOM = {
canvas: document.getElementById("canvas"),
ctx: document.getElementById("canvas").getContext("2d"),
select: document.getElementById("control-select"),
createBtn: document.getElementById("control-create"),
oname: document.getElementById("control-name"),
oresult: document.getElementsByClassName("control-result")[0],
}
複製程式碼
定義兩個人的圖片
var boyImg = new Image(), girlImg = new Image();
boyImg.src = "images/long.jpg";
girlImg.src = "images/sanye.jpg";
複製程式碼
把常用的工具方法寫在一個工具類裡
const UTILS = (function(){
let clearForm = () => {
// 清空表單
DOM.oname.value = "";
DOM.oresult.innerHTML = "";
}
return {
clearForm: clearForm,
}
})();
複製程式碼
把事件繫結DOM集合寫在一個函式內
var eventBind = () => {
// 初始畫布渲染
boyImg.onload = () => {
DOM.ctx.drawImage(boyImg,0,0,250,250);
}
// 選擇人物
DOM.select.onchange = () => {
UTILS.clearForm();
if(DOM.select.value === "立花瀧"){
DOM.ctx.drawImage(boyImg,0,0,250,250);
}else if(DOM.select.value === "宮水三葉"){
DOM.ctx.drawImage(girlImg,0,0,250,250);
}else{
alert("請求非法");
}
}
// 畫布實時更新
DOM.oname.oninput = () => {
imageHandle();
}
// 生成圖片處理
DOM.createBtn.onclick = function(){
if(DOM.oname.value == ""){
alert("喂,真的什麼都不寫嗎?");
}else{
DOM.createBtn.innerHTML = "生成中.";
DOM.createBtn.setAttribute("disabled","disabled");
DOM.createBtn.style.cursor = "not-allowed";
setTimeout(function(){
imageHandle();
DOM.createBtn.innerHTML = "生成圖片";
DOM.createBtn.removeAttribute("disabled");
DOM.createBtn.style.cursor = "pointer";
DOM.oresult.innerHTML = "生成成功,<a href='"+DOM.canvas.toDataURL("image/png")+"' download='avatar'>點選下載</a>"
},2000);
}
}
}
複製程式碼
編寫圖片處理函式
function imageHandle(){
// 圖片處理
let text = DOM.oname.value;
DOM.ctx.font = "18px 宋體";
if(DOM.select.value === "立花瀧"){
DOM.ctx.drawImage(boyImg,0,0,250,250);
drawText(text,117,60,1);
}else if(DOM.select.value === "宮水三葉"){
DOM.ctx.drawImage(girlImg,0,0,250,250);
drawText(text,105,50,1);
}else{
alert("請求非法!");
}
}
複製程式碼
編寫文書處理函式
function drawText(t,x,y,w){
// 文書處理
var chr = t.split("");
var temp = "";
var row = [];
DOM.ctx.textBaseline = "middle";
for(var a = 0; a < chr.length; a++){
if( !DOM.ctx.measureText(temp).width < w ){
row.push(temp);
temp = "";
}
temp += chr[a];
}
row.push(temp);
for(var b = 0; b < row.length; b++){
DOM.ctx.fillText(row[b],x,y+(b+1)*20);
}
}
複製程式碼
入口函式
var main = () => {
// 入口
eventBind();
}
main();
複製程式碼
GITHUB
第一次寫文章,如果有不對的地方請大家幫忙指出來.