實(shí)現(xiàn)思路
- 給canvas元素添加寬高号俐,及背景色屬性皆怕。
- 添加一個(gè)button元素娃殖,用于切換繪制和擦除功能值戳。
- 分別給這兩個(gè)元素添加鼠標(biāo)事件監(jiān)聽(tīng),各自實(shí)現(xiàn)所需要的功能炉爆。在不同的鼠標(biāo)事件中堕虹,實(shí)現(xiàn)不同的效果。
代碼
1.CSS
<style>
canvas{
background:"#eee";
}
</style>
2.HTML
//注意:canvas的寬高只能寫在標(biāo)簽上叶洞,不能寫在css樣式中鲫凶,
//html的屬性值可以省略單位。
<canvas width="1200" height="600"></canvas>
<button>擦除</button>
3.JS
//獲取canvas元素
var canvas = document.querySelector("canvas");
//canvas元素有一個(gè)getContext()的方法衩辟,這個(gè)方法是用來(lái)獲得渲染上下文和它的繪畫功能螟炫。
//此案例是對(duì)于2D圖像而言,用法如下所示
var ctx = canvas.getContext("2d");
//獲取button元素
var bn = document.querySelector("button");
//設(shè)置邊線顏色
ctx.strokeStyle="red";
//設(shè)置一個(gè)bool值艺晴,值為true 代表擦除昼钻,值為false代表繪制,默認(rèn)false
var bool=false;
//給畫布添加一個(gè)鼠標(biāo)按下的事件監(jiān)聽(tīng)
canvas.addEventListener("mousedown",mouseHandler);
//給按鈕添加一個(gè)鼠標(biāo)點(diǎn)擊的事件監(jiān)聽(tīng)
bn.addEventListener("click",clickHandler);
function clickHandler(e){
//當(dāng)按鈕被點(diǎn)擊時(shí)封寞,為擦除功能然评,切換bool值和對(duì)應(yīng)的按鈕內(nèi)容
bool = !bool;
if(bool){
bn.textContent="繪制";
}else{
bn.textContent="擦除";
}
}
function mouseHandler(e){
if(!bool){
//當(dāng)bool為false時(shí),執(zhí)行繪制功能狈究,否則擦除功能碗淌。
drawLine(e);
}else{
clearLine(e);
}
}
function clearLine(e){
if(e.type === "mousedown"){
//設(shè)置一個(gè)清除矩形,左上角坐標(biāo)為前面兩個(gè)參數(shù)抖锥,
//第三個(gè)參數(shù)是清除矩形的寬度亿眠,最后一個(gè)參數(shù)是清除矩形的高度,都是以像素為單位磅废。
//e.offsetX,e.offsetY 為當(dāng)前鼠標(biāo)按下的坐標(biāo)
ctx.clearRect(e.offsetX,e.offsetY,70,70);
//添加兩個(gè)事件監(jiān)聽(tīng)
canvas.addEventListener("mousemove",mouseHandler);
canvas.addEventListener("mouseup",mouseHandler);
}else if(e.type === "mousemove"){
ctx.clearRect(e.offsetX,e.offsetY,70,70);
}else if(e.type === "mouseup"){
//鼠標(biāo)抬起纳像,清除監(jiān)聽(tīng)功能
canvas.removeEventListener("mousemove",mouseHandler);
canvas.removeEventListener("mouseup",mouseHandler);
}
}
function drawLine(e){
if(e.type === "mousedown"){
//起始一條路徑,或者重繪當(dāng)前路徑
ctx.beginPath();
//起始點(diǎn)
ctx.moveTo(e.offseeeetX,e.offsetY);
canvas.addEventListener("mousemove",mouseHandler);
canvas.addEventListener("mouseup",mouseHandler);
}else if(e.type === "mousemove"){
//終點(diǎn)
ctx.lineTo(e.offsetX,e.offsetY);
//開(kāi)始繪制
ctx.stroke();
}else if(e.type === "mouseup"){
canvas.removeEventListener("mousemove",mouseHandler);
canvas.removeEventListener("mouseup",mouseHandler);
}
}
演示效果
image.png