這篇文章給大家分享的是有關怎樣使用html5 canvas制作涂鴉畫板的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
清空畫板
Line width : 1
3
5
7
9
11
Color : black
blue
red
green
yellow
gray
HTML代碼
我們需要一個用于繪畫的canvas元素和一些用于選擇操作的下拉框:
JAVASCRIPT
我們的涂鴉畫板js腳本主要有三個函數:
InitThis():該方法用于初始化所需要的鼠標事件。
Draw():該方法在鼠標左鍵被按下時每次移動都會畫一條線。
clearArea():該方法用于清空畫板上的所有線條。
var mousePressed = false;
var lastX, lastY;
var ctx;
function InitThis() {
ctx = document.getElementById('myCanvas').getContext("2d");
$('#myCanvas').mousedown(function (e) {
mousePressed = true;
Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, false);
});
$('#myCanvas').mousemove(function (e) {
if (mousePressed) {
Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, true);
}
});
$('#myCanvas').mouseup(function (e) {
mousePressed = false;
});
$('#myCanvas').mouseleave(function (e) {
mousePressed = false;
});
}
function Draw(x, y, isDown) {
if (isDown) {
ctx.beginPath();
ctx.strokeStyle = $('#selColor').val();
ctx.lineWidth = $('#selWidth').val();
ctx.lineJoin = "round";
ctx.moveTo(lastX, lastY);
ctx.lineTo(x, y);
ctx.closePath();
ctx.stroke();
}
lastX = x; lastY = y;
}
function clearArea() {
// Use the identity matrix while clearing the canvas
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}
感謝各位的閱讀!關于“怎樣使用html5 canvas制作涂鴉畫板”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。