首先html文件中如下写,图片的话,自己随便找一张。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.btn ul{
list-style: none;
}
.btn ul li{
float: left;
margin-left: 20px;
}
</style>
</head>
<body style="background:url(./img/1.jpg)">
<div>
<canvas class="board" width="600px" height="300px" style="border:1px solid grey"></canvas>
<div class="btn">
<ul>
<li>
<button class="pen">画笔</button>
</li>
<li>
<button class="earse">橡皮擦</button>
</li>
<li>
<button class="pre">上一步</button>
</li>
<li>
<button class="next">下一步</button>
</li>
</ul>
</div>
</div>
<script src="./js/jQuery.js"></script>
<script src="./js/index.js"></script>
</body>
</html>
js_45">然后js文件
var width = $('.board').width()
var height = $('.board').height()
var left = $('.board').offset().left
var top = $('.board').offset().top
var imgList = []
var step = -1
var $board = $('.board')[0]
var ctx = $board.getContext("2d");
var earseFalse = false
var flag = false
ctx.lineWidth = '5'
window.onload = function() {
$('.pen').click(function(){
ctx.globalCompositeOperation="source-over"
ctx.lineWidth = '5'
ctx.strokeStyle = 'black'
})
$('.earse').click(function(){
ctx.globalCompositeOperation="destination-out"
ctx.strokeStyle = 'white'
ctx.lineWidth = '20'
})
$('.board').mousedown(function(e){
flag = true
ctx.beginPath();
ctx.moveTo(e.clientX-left,e.clientY.top)
})
$('.board').mousemove(function(e){
if(flag){
ctx.lineTo(e.clientX-1,e.clientY-1);
ctx.stroke()
}
})
$('.board').mouseup(function(e){
ctx.closePath()
history()
flag = false
})
$('.pre').click(function(){
if(step >= 0){
step--
clearCanvas()
var img = new Image()
img.src = imgList[step]
img.onload= function(){ctx.drawImage(img,0,0)}
}else{
alert('没有上一步了')
}
})
$('.next').click(function(){
if(step<imgList.length-1){
step++
clearCanvas()
var img = new Image()
img.src = imgList[step]
img.onload = function(){ctx.drawImage(img,0,0)}
}else{
alert('没有下一步了')
}
})
function clearCanvas(){
$('.board').attr('height',height)
}
function history(){
step++
if(step<imgList.length){
imgList.length = step
}
imgList.push($(".board").get(0).toDataURL())
}
}
最后说一下globalCompositeOperation的集中属性值代表的意思
- source-over:默认。在目标图像上显示源图像。
- source-atop:在目标图像顶部显示源图像。源图像位于目标图像之外的部分是不可见的。
- source-in:在目标图像中显示源图像。只有目标图像内的源图像部分会显示,目标图像是透明的。
- source-out :在目标图像之外显示源图像。只会显示目标图像之外源图像部分,目标图像是透明的。
- destination-over:在源图像上方显示目标图像。
- destination-atop:在源图像顶部显示目标图像。源图像之外的目标图像部分不会被显示。
- destination-in:在源图像中显示目标图像。只有源图像内的目标图像部分会被显示,源图像是透明的。
- destination-out:在源图像外显示目标图像。只有源图像外的目标图像部分会被显示,源图像是透明的。
- lighter:显示源图像 + 目标图像。
- copy:显示源图像。忽略目标图像。
- xor :使用异或操作对源图像与目标图像进行组合。