h5绘制图画
参考网站资料编写的绘图
<!DOCTYPE html>
<
html
lang
=
"en"
>
<
head
>
<
meta
charset
=
"UTF-8"
>
<
title
>cavans</
title
>
<
style
>
body{
margin:0;
padding:0;
background: #f1f1f1;
}
.box{display: flex;justify-content: center;}
#canvas{
background: #EBE9BB;
width:480px;
height:480px;
}
.color{
overflow: hidden;
display: flex;
justify-content: center;
align-items: center;
padding: 10px 0;
}
.color span{
display: block;
width: 40px;
height: 40px;
border-radius: 50%;
margin-right: 10px;
border:3px solid transparent;
}
.color .active{
border: 3px solid darkmagenta;
}
.clear{text-align: center;}
.clear button{
padding: 7px 15px;
background: #008000;
border-radius: 5px;
color: #fff;
font-size: 5vw;
border: 0;
}
#btn{
background: #ff328e!important;
}
</
style
>
<
script
src
=
"https://cdn.bootcss.com/jquery/1.11.3/jquery.min.js"
></
script
>
</
head
>
<
body
>
<!--画布-->
<
div
class
=
"box"
>
<
canvas
id
=
"canvas"
width
=
"480"
height
=
"480"
></
canvas
>
</
div
>
<
div
class
=
"color"
>
<
span
class
=
"active"
></
span
>
<
span
></
span
>
<
span
></
span
>
<
span
></
span
>
<
span
></
span
>
<
span
></
span
>
</
div
>
<
div
class
=
"clear"
>
<
button
id
=
"eraser"
>橡皮擦</
button
>
<
button
id
=
"btn"
>清除画布</
button
>
</
div
>
<
script
>
$(function(){
var x1,y1,x2,y2,a=10;
//定义画板cavans
var canvas = document.getElementById("canvas");
var w=$(canvas).prop('width');
var h=$(canvas).prop('height');
var ctx = canvas.getContext("2d");
//颜色初始化
var colors="green";
var color=["black","green","red","gray","blue","yellow"];
for(var i=0;i<
color.length
;i++){
$('.color span').eq(i).css('background',color[i])
};
//点击颜色选中
$('.color span').on('click',function(){
$(this).siblings().removeClass("active");
$(this).addClass('active');
colors=$(this)[0].style.background;
console.log(colors);
a
=
10
;
tapClip();
});
//在画板上画画的函数
function tapClip(){
//笔触圆滑
ctx.lineCap
=
"round"
;
ctx.lineJoin
=
"round"
;
ctx.lineWidth
=
a
;
ctx.strokeStyle
=
colors
;
canvas.addEventListener('mousedown' , function(e){
e.preventDefault();
x1
=
e
.clientX-canvas.offsetLeft;
y1
=
e
.clientY-canvas.offsetTop;
ctx.beginPath()
ctx.moveTo(x1,y1);
ctx.lineTo(x1+1,y1+1); //考虑到点击时能画出一个点
ctx.stroke();
canvas.addEventListener('mousemove' , tapmoveHandler);
canvas.addEventListener('mouseup' , function(e){
canvas.removeEventListener('mousemove' , tapmoveHandler);
});
});
//移动
function tapmoveHandler(e){
e.preventDefault();
x2
=
e
.clientX-canvas.offsetLeft;
y2
=
e
.clientY-canvas.offsetTop;
ctx.moveTo(x1,y1);
ctx.lineTo(x2,y2);
ctx.stroke();
x1
=
x2
;
y1
=
y2
;
}
}
tapClip();
//橡皮擦
$("#eraser").click(function(){
colors
=
"#EBE9BB"
;
a
=
30
;
tapClip();
});
//点击清除画布
$("#btn").click(function(){
ctx.clearRect(0,0,w,h);
})
});
</script>
</
body
>
</
html
>
版权声明:本文由Web学习之路发布,如需转载请注明出处。