之前学习h5和css3大部分时间都是看书,看完了没啥感觉,最近在联系各种demo,感觉虽然敲代码会让你觉得学得慢,但是学的劳呀,而且做出了想要的demo那成就感真实棒棒哒!
下面就是我学习canvas写的画图小程序demo参考了航哥学习h5和css3可以好好跟着他练习
>
=====>
<style>
*{
margin: 0;
padding: 0;
}
.wrap{
width: 500px;
height:500px;
padding: 10px 0;
margin: 0 auto;
text-align: center;
}
.main-header{
display:flex;
padding: 10px 0;
}
#canvas{
border:1px solid #000;
}
.main-color,.main-size{
width:250px;
height: 80px;
background-color: #ccc;
border:1px solid #ccf;
text-align: center;
padding: 10px 0;
,{
display: flex;
list-style: none;
width: 30px;
height:30px;
padding: 5px;
;
justify-content:center;
align-items:center;
,.main-size ul {
padding: 10px 0;
display: flex;
justify-content:center;
}
.redColor{
background-color: rgba(255,0,0,1);
}
.blueColor{
background-color: rgba(255,0,247,1);
}
.yellowColor{
background-color: rgba(255,235,59,1);
,{
border:1px solid #000;
opacity:0.5;
}
.smallLine{
width:20px;
height:20px;
display: block;
border-radius: 100%;
background-color:#607d8b;
}
.middleLine{
width:25px;
height:25px;
display: block;
border-radius: 100%;
background-color:#607d8b;
}
.largeLine{
width:30px;
height:30px;
display: block;
border-radius: 100%;
background-color:#607d8b;
}
#showImg{
display: none;
}
="text/javascript">
window.onload = function(){
canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
canvas.onmousedown = startDrawing;
canvas.onmouseup = stopDrawing;
canvas.onmousemove = isDrawing;
var isDrawing=false;
{
isDrawing=
true;
// 创建一个绘图路径
context.beginPath();
// 把画笔移到鼠标位置
context.moveTo(e.pageX - canvas.offsetLeft,e.pageY -canvas.offsetTop)
}
{
if(isDrawing){
// v找到鼠标的最新位置
x = e.pageX - canvas.offsetLeft;
y = e.pageY -canvas.offsetTop;
context.lineTo(x,y);
context.stroke();
}
}
{
isDrawing=
false;
}
}
{
// 获取当前选中元素的父元素,先统一清空其他li的边框
var chilNodes=that.parentNode.childNodes;
var j=chilNodes.length;
for (i=
0;i<j;i++)
// 过滤节点中的文本节点
if(chilNodes[i].nodeType!==
3){
chilNodes[i].style.border =
'';
}
that.style.border =
'1px #000 solid';
//获取当前选择区域的颜色,这里用了计算属性,可能是背景颜色是通过类名设置的,直接用.style获取不到
var thatColor = window.getComputedStyle(that,
null).backgroundColor
context.strokeStyle = thatColor;
}
{
// 由于点击的元素是a所以取ul得两次获取父节点
var chilNodes=that.parentNode.parentNode.childNodes;
var j=chilNodes.length;
for (i=
0;i<j;i++)
if(chilNodes[i].nodeType!==
3){
chilNodes[i].style.border =
'';
}
that.parentNode.style.border =
'1px #000 solid'
context.lineWidth = temp;
}
{
var img = document.getElementById(
'img')
var showImg = document.getElementById(
'showImg')
img.src = canvas.toDataURL();
showImg.style.display =
'block';
}
{
context.clearRect(
0,
0,canvas.width,canvas.width);
var showImg = document.getElementById(
'showImg');
showImg.style.display =
'none';
}
===>
==>
>>
>画笔粗细>==>
==>==>>
========>
>