canvas画板小练习
<div class="d">
<div>
画板
</div>
<canvas id="myCanvas" width="500" height="200" class="myCanvas "></canvas>
</div>
<div class="d">
<div>
展示
</div>
<img src="" alt="" id="imgCanvas" class="imgCanvas">
</div>
<div>
<button id="clearBtn">清除</button>
<button id="saveBtn">保存图片</button>
<button id="deleBtn">清除图片</button>
<input type="color" name="color" id="color" >
<label for="">
画笔粗细
<input type="number" id="canvasBrush" value="1">
</label>
</div>
/** @type {HTMLCanvasElement} */
const canvas = document.getElementById('myCanvas')
const color = document.getElementById('color')
const clearBtn = document.getElementById('clearBtn')
const saveBtn = document.getElementById('saveBtn')
const deleBtn = document.getElementById('deleBtn')
const imgCanvas = document.getElementById('imgCanvas')
const canvasBrush = document.getElementById('canvasBrush')
const cxt = canvas.getContext("2d");
let isDraw = false;
let whiteCanvas = '';
// 自运行函数前用分号
// 防止进入 会有图片裂开的图片
(function(){
imgCanvas.src = canvas.toDataURL('image/png')
whiteCanvas = canvas.toDataURL('image/png')
})()
// 初始化画笔宽度
cxt.lineWidth = 1
// 修改画笔颜色
color.addEventListener('change', function(e) {
cxt.beginPath()
cxt.strokeStyle = e.target.value
})
// 记录画笔起点位置
canvas.addEventListener('mousedown', function(e) {
const {clientX, clientY} = getCanvasXY(e.clientX,e.clientY)
isDraw = true
setDraw({x:clientX,y:clientY})
})
// 鼠标按键弹起时不画
canvas.addEventListener('mouseup', function() {
isDraw = false
})
// 鼠标按下且在canvas内移动作画
canvas.addEventListener('mousemove', function(e) {
if (!isDraw) return
const {clientX, clientY} = getCanvasXY(e.clientX,e.clientY)
setDraw(null,{x:clientX,y:clientY})
})
// 清除画布内容
clearBtn.addEventListener('click',function() {
cxt.beginPath()
cxt.clearRect(0,0,500,500)
})
// 修改画笔粗细
canvasBrush.addEventListener('change',function(e) {
cxt.beginPath()
cxt.lineWidth = e.target.value
})
function setDraw(start,end) {
if (!end) {
const {x,y} = start
cxt.moveTo(x,y)
}
if (!start) {
const {x,y} = end
cxt.lineTo(x,y)
}
cxt.stroke()
imgCanvas.src = canvas.toDataURL('image/png')
}
function getCanvasXY(x,y) {
// 减去canvas的偏移距离
const left = canvas.offsetLeft
const top = canvas.offsetTop
return {
clientX: x - left,
clientY: y - top,
x: x - left,
y: y - top
}
}
saveBtn.addEventListener('click',function() {
var fileName = 'testImg.png';
var blob = dataURLtoBlob(imgCanvas.src);
var objurl = URL.createObjectURL(blob);
var alink = document.createElement("a");
alink.href = objurl;
alink.download = fileName;
alink.click();
function dataURLtoBlob(dataurl) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
}
})
deleBtn.addEventListener('click',function() {
imgCanvas.src = whiteCanvas
})