html5 canvas 画图

2015年03月11日 15:29 0 点赞 0 评论 更新于 2025-11-21 13:47

以下是使用 HTML5 Canvas 实现画图功能的代码,仅供参考学习。

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>用 HTML5 Canvas 做一个画图板</title>
<style type="text/css">
body, p {
margin: 0;
padding: 0;
}
.content {
display: block;
font-size: 14px;
margin: 0 2px;
padding: 0 15px;
line-height: 150%;
color: #1A2536;
font-family: "PT Serif", Georgia, Times, "Times New Roman", "Heiti SC", "Microsoft Yahei", "微软雅黑", "宋体", serif;
}
</style>
</head>
<body>
<div id="content">
<canvas id="the_stage" width="520" height="350" style="border: 1px solid #999;"></canvas>
</div>
<script type="text/javascript">
function Draw(arg) {
// 判断传入的参数类型
if (arg.nodeType) {
this.canvas = arg;
} else if (typeof arg === 'string') {
this.canvas = document.getElementById(arg);
} else {
return;
}
this.init();
}

Draw.prototype = {
init: function() {
var that = this;
// 判断浏览器是否支持 Canvas
if (!this.canvas.getContext) {
return;
}
// 获取 2D 绘图上下文
this.context = this.canvas.getContext('2d');
// 禁止在画布上选择文本
this.canvas.onselectstart = function() {
return false;
};
// 监听鼠标按下事件
this.canvas.onmousedown = function() {
that.drawBegin(event);
};
},
drawBegin: function(e) {
var that = this;
// 获取画布相对于视口的位置信息
var stage_info = this.canvas.getBoundingClientRect();
// 清除文本选中状态
if (window.getSelection) {
window.getSelection().removeAllRanges();
} else {
document.selection.empty();
}
// 将绘图起点移动到鼠标点击位置
this.context.moveTo(
e.clientX - stage_info.left,
e.clientY - stage_info.top
);
// 监听鼠标移动事件
document.onmousemove = function() {
that.drawing(event);
};
// 监听鼠标松开事件
document.onmouseup = this.drawEnd;
},
drawing: function(e) {
// 获取画布相对于视口的位置信息
var stage_info = this.canvas.getBoundingClientRect();
// 绘制线条到鼠标当前位置
this.context.lineTo(
e.clientX - stage_info.left,
e.clientY - stage_info.top
);
// 绘制线条
this.context.stroke();
},
drawEnd: function() {
// 释放鼠标移动和松开事件的监听,释放内存
document.onmousemove = document.onmouseup = null;
}
};

// 创建 Draw 实例并传入画布 ID
var draw = new Draw('the_stage');
</script>
</body>
</html>

代码解释

  1. HTML 部分

    • 定义了一个 canvas 元素,用于绘制图形,其 ID 为 the_stage,宽度为 520px,高度为 350px,并添加了一个 1px 的灰色边框。
  2. JavaScript 部分

    • Draw 构造函数:用于初始化绘图对象,可以接受一个 DOM 节点或一个字符串(元素 ID)作为参数。
    • init 方法:初始化绘图上下文,判断浏览器是否支持 Canvas,禁止在画布上选择文本,并监听鼠标按下事件。
    • drawBegin 方法:在鼠标按下时,清除文本选中状态,将绘图起点移动到鼠标点击位置,监听鼠标移动和松开事件。
    • drawing 方法:在鼠标移动时,绘制线条到鼠标当前位置,并调用 stroke 方法绘制线条。
    • drawEnd 方法:在鼠标松开时,释放鼠标移动和松开事件的监听,释放内存。

通过以上代码,你可以在 HTML5 Canvas 上实现简单的画图功能。