console
var canvas=document.querySelector('#canvas');
var buttons=document.querySelectorAll('button');
var canvas=document.getElementById('canvas');
ctx=canvas.getContext('2d');
var img=document.getElementById("img");
img.onload=function(){
ctx.drawImage(img,0,0)
}
beginDraw= function(){
if(buttons[0].style.backgroundColor==='red'){
buttons[0].style.backgroundColor='';
canvas.removeEventListener('mousedown',star);
}else{
buttons[0].style.backgroundColor='red';
canvas.addEventListener('mousedown',star);
}
}
bianhong=function(){
if(buttons[1].style.backgroundColor==='red'){
buttons[1].style.backgroundColor='';
ctx.strokeStyle='#000000'
}else{
buttons[1].style.backgroundColor='red'
ctx.strokeStyle='red'
}
}
bianlan=function(){
if(buttons[2].style.backgroundColor==="blue"){
buttons[2].style.backgroundColor='';
ctx.strokeStyle='red'
}else{
buttons[2].style.backgroundColor="blue"
ctx.strokeStyle='blue'
}
}
canvas.onmouseup=function(e){
canvas.removeEventListener('mouseleave',leave);
canvas.removeEventListener('mousemove',draw);
}
function star(e){
ctx.beginPath()
ctx.lineWidth='8.0'
ctx.lineJion='round'
ctx.lineCap='round'
const{
offsetX:starX,
offsetY:starY,
}=e
ctx.moveTo(starX,starY);
canvas.addEventListener('mousemove',draw);
canvas.addEventListener('mouseleave',leave);
}
function leave(){
canvas.removeEventListener('mouseleave',leave);
canvas.removeEventListener('mousemove',draw);
}
function draw(e){
const{
offsetX:curX,
offsetY:curY,
}=e
ctx.lineTo(curX,curY)
ctx.stroke()
}
<div class="draw-boar" style="border:2px solid #ccc">
<img src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2F1113%2F011620120T1%2F200116120T1-6-1200.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1660268494&t=25a26cc1c0ef9b66b49e2ef547c1be2b" width="300" height="300" id="img">
<hr>
<canvas id="canvas" width="300" height="300"></canvas>
<button onclick="beginDraw()">画笔</button>
<button onclick="bianhong()">红色</button>
<button onclick="bianlan()">蓝色</button>
<button onclick="{ctx.clearRect(0,0,300,300)}">清空</button>
<button id="btn" onclick="convertCanvasToImage()">点我下载</button>
<button id="save" >保存</button>
<hr>
</div>
.draw-boar {
width: 300px;
margin: 30px auto;
}
img{
display: none
}