js實現鼠標籤名,不用任何插件,超值

// 加載畫布
$(function(){
    $("body").append(
    '<div id="canvasParcel" style="position: absolute;top: 25%;left:25%;cursor:default;z-index:999999999">'+
    '<canvas id="canvas" width="800px" height="300px"></canvas>'+
    '<button onclick="exportSignature(this)">確定</button>'+
    '<button onclick="empty(this)">清空</button>'+
    '</div>'
    );
  }
);


var canvaDom = document.getElementById("canvas");   // 畫布對象
var context = canvaDom.getContext("2d");            // 畫板的上下文
var canvasX = canvaDom.getBoundingClientRect().left;// 畫板的座標x
var canvasY = canvaDom.getBoundingClientRect().top; // 畫板的座標y
context.fillStyle = "black";                        // 畫布背景色
context.lineWidth = 4;                              // 線的寬度
context.strokeStyle = "white";                      // 線的顏色
context.fillRect(0, 0, canvaDom.width, canvaDom.height);// 畫板的範圍


canvaDom.addEventListener("mousedown", down, false);// 鼠標按下去的事件
canvaDom.addEventListener("mousemove", draw, false);// 鼠標移動事件
canvaDom.addEventListener("mouseup", up, false);    // 鼠標鬆開事件


var onoff = false;  // 鎖定開關
var oldx = canvasX; // 起始座標x
var oldy = canvasY; // 起始座標y
var newx;           // 結束座標x
var newy;           // 結束座標y


// 鼠標按下
function down(event) {
    onoff = true;                   // 打開開關
    oldx = event.clientX -canvasX;  // 鼠標在畫板中點擊的X的座標
    oldy = event.clientY -canvasY;  // 鼠標在畫板中點擊的Y的座標
    context.beginPath();            // 開始路徑
}


// 鼠標移動
function draw(event) {
    // 開關
    if (onoff) {
        newx = event.clientX-canvasX;
        newy = event.clientY-canvasY;
        context.moveTo(oldx, oldy); // 線的起點座標
        context.lineTo(newx, newy); // 線的始點座標
        context.stroke();           // 初始化到畫布中
        oldx = newx;
        oldy = newy;
    }
}
// 鼠標離開
function up() {
    onoff = false;      // 關閉開關
    context.closePath();// 關閉路徑
}


// 清空
function empty() {
context.clearRect(0,0,canvaDom.width,canvaDom.height);  // 清空的範圍
context.fillRect(0, 0, canvaDom.width, canvaDom.height);// 重設的範圍
}


//導出信息
function exportSignature() {
    // 作者標記
    context.font = "20px 宋體";
    context.fillStyle = 'white';
    context.fillText('草先生'+new Date().toLocaleString(), 5, canvaDom.height-5);
    var exportImg = canvas.toDataURL("image/jpeg",0.1);// 0.1代表壓縮的比率,默認爲1
    console.info(exportImg);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章