html5的canvas实现网页画图步骤:
①定义画布(html5)②设置画布样式(CSS)③js准备绘图的上下文环境④js绘图
效果如下:

点击按钮可以改变画笔颜色和画笔粗细大小。随便画的_(:з」∠)_不要嫌弃我手抖

代码如下:
.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#myCanvas{
border:1px solid black;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="860" height="480"></canvas><!-- 此处宽度高度不能带有px单位 -->
<p>画笔颜色:</p>
<button onclick="yellow()">黄色</button>
<button onclick="black()">黑色</button>
<button onclick="red()">红色</button>
<button onclick="green()">绿色</button>
<button onclick="blue()">蓝色</button>
<button onclick="pink()">粉色</button>
<button onclick="orange()">橙色</button>
<p>画笔粗细:</p>
<button onclick="thin()">细画笔</button>
<button onclick="mid()">中画笔</button>
<button onclick="thick()">粗画笔</button>
</body>
<script src="1.js">
</script>
</html>
.js
var canvas,pen;
canvas=document.getElementById('myCanvas');
pen=canvas.getContext('2d');//获取上下文环境,2d画图
pen.lineWidth=1;//画笔的粗细
pen.strokeStyle="blue";//画笔颜色
var mousePress=false;//判断鼠标是否按下,初始值为没有按下
var last=null;//鼠标结束的点,初始为空
function thin(){
pen.lineWidth=1;
}
function mid(){
pen.lineWidth=5;
}
function thick(){
pen.lineWidth=10;
}
function yellow(){
pen.strokeStyle="yellow";
}
function black(){
pen.strokeStyle="black";
}
function red(){
pen.strokeStyle="red";
}
function green(){
pen.strokeStyle="green";
}
function blue(){
pen.strokeStyle="blue";
}
function pink(){
pen.strokeStyle="pink";
}
function orange(){
pen.strokeStyle="orange";
}
function pos(event){//鼠标取得点
var ex,ey;
ex=event.clientX;
ey=event.clientY;
return{
x:ex,
y:ey
}
}
function start(event){//开始绘图函数
mousePress=true;//鼠标按下
}
function draw(event){//当鼠标按下且移动才会绘图
if(!mousePress) return;
var xy=pos(event);
if(last!=null){//看结束点是否为空
//不为空证明有开始点结束点,方才开始绘图
pen.beginPath();
pen.moveTo(last.x,last.y);//上次绘图停止的点
pen.lineTo(xy.x,xy.y);//本次绘图的终点
pen.stroke();
}
last=xy;//把本次绘图终点变为上次绘图的重点
//再次绘图的时候就能从本次绘图终点开始
}
function finish (event) {
mousePress=false;
last=null;
}
canvas.onmousedown=start;
canvas.onmousemove=draw;
canvas.onmouseup=finish;
本文介绍了如何使用HTML5的Canvas元素结合CSS和JavaScript来实现一个简单的网页画图功能。通过定义画布、设置样式和利用JavaScript进行绘图操作,用户可以点击按钮改变画笔颜色和粗细,自由地在网页上绘画。
&spm=1001.2101.3001.5002&articleId=105163775&d=1&t=3&u=494b35aa8d154105bbab29028c94b76f)
1万+

被折叠的 条评论
为什么被折叠?



