当前位置: > > > HTML5 - 使用Canvas做一个在线画图程序(支持把画布保存为图像)

HTML5 - 使用Canvas做一个在线画图程序(支持把画布保存为图像)

1,在线画图板的开发
(1)页面加载后,我们取得<canvas>对象,为它添加一些处理函数,以便处理不同鼠标操作导致的JavaScript事件:onmousedownonmouseuponmouseoutonmousemove
(2)画布上方了两个工具栏可以选择笔画颜色和笔画粗细。点击里面的<img>元素,会调用对应绑定的方法,从而将 strokeStyle 属性设置不同的颜色,或将 lineWidth 属性设置不同的粗细。

在线Demo如下:
- 颜色 -
红色 绿色 蓝色
- 粗细 -
细 中 粗
- 操作 -

使用右键保存图像 ...

--- paint.html ---
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Paint</title>
  <link rel="stylesheet" href="Paint.css">
  <script>
    var canvas;
	var context;

	// 初始化
	window.onload = function() {
	  // 获取画布已经绘图上下文
	  canvas = document.getElementById("drawingCanvas");
	  context = canvas.getContext("2d");

	  // 画布添加鼠标事件
	  canvas.onmousedown = startDrawing;
	  canvas.onmouseup = stopDrawing;
	  canvas.onmouseout = stopDrawing;
	  canvas.onmousemove = draw;
	};

	// 记录当前是否在画图
	var isDrawing = false;

	// 开始画图
	function startDrawing(e) {
	  isDrawing = true;
	  // 创建一个新的绘图路径
	  context.beginPath();
	  // 把画笔移动到鼠标位置
	  context.moveTo(e.pageX - canvas.offsetLeft, e.pageY - canvas.offsetTop);
	}

	// 停止画图
	function stopDrawing() {
	  isDrawing = false;
	}

	//画图中
	function draw(e) {
	  if (isDrawing == true) {
		// 找到鼠标最新位置
		var x = e.pageX - canvas.offsetLeft;
		var y = e.pageY - canvas.offsetTop;
		// 画一条直线到鼠标最新位置
		context.lineTo(x, y);
		context.stroke();	
	  }
	}

	// 保存之前选择的颜色的画笔 <img> 元素标签
	var previousColorElement;

	// 改变画笔颜色
	function changeColor(color, imgElement) {	  
	  context.strokeStyle = color;
	  // 将当前画笔的 <img> 元素标签设置为选中样式
	  imgElement.className = "Selected";
	  // 将之前的画笔的 <img> 元素标签恢复默认样式
	  if (previousColorElement != null) previousColorElement.className = "";
	  previousColorElement = imgElement;
	}

	// 保存之前选择的粗细的画笔 <img> 元素标签
	var previousThicknessElement;

	// 改变画笔粗细
	function changeThickness(thickness, imgElement) {	  
	  context.lineWidth = thickness;
	  // 将当前画笔的 <img> 元素标签设置为选中样式
	  imgElement.className = "Selected";
	  // 将之前的画笔的 <img> 元素标签恢复默认样式
	  if (previousThicknessElement != null) previousThicknessElement.className = "";
	  previousThicknessElement = imgElement;
	}

	// 清除画布
	function clearCanvas() {
	  context.clearRect(0, 0, canvas.width, canvas.height);
	}

	// 保存画布
	function saveCanvas() { 
	  // 找到预览的 <img> 元素标签
	  var imageCopy = document.getElementById("savedImageCopy");
	  // 将画布内容在img元素中显示
	  imageCopy.src = canvas.toDataURL();  
	  // 显示右键保存的提示
	  var imageContainer = document.getElementById("savedCopyContainer");
	  imageContainer.style.display = "block";
	}
  </script>
</head>

<body>
  <div class="Toolbar">
    - 颜色 -<br>
    <img id="redPen" src="pen_red.gif" alt="红色" onclick="changeColor('rgb(212,21,29)', this)">
    <img id="greenPen" src="pen_green.gif" alt="绿色" onclick="changeColor('rgb(131,190,61)', this)"> 
    <img id="bluePen" src="pen_blue.gif" alt="蓝色" onclick="changeColor('rgb(0,86,166)', this)">
  </div>
  <div class="Toolbar">
    - 粗细 -<br>
    <img src="pen_thin.gif" alt="细" onclick="changeThickness(1, this)">
    <img src="pen_medium.gif" alt="中" onclick="changeThickness(5, this)"> 
    <img src="pen_thick.gif" alt="粗" onclick="changeThickness(10, this)">
  </div>
  <div class="CanvasContainer">
    <canvas id="drawingCanvas" width="400" height="200"></canvas>
  </div>
  <div class="Toolbar">
    - 操作 -<br>
    <button onclick="saveCanvas()">保存图像</button>
    <button onclick="clearCanvas()">清除图像</button>
    <div id="savedCopyContainer">
      <img id="savedImageCopy"><br>
      使用右键保存图像 ...
    </div>
  </div>
</body>
</html>

--- paint.css ---
body {
  background: white;
}

.Toolbar {
  float: left;
  font-family: 'Trebuchet MS'; 
  font-size: 14px;
  font-variant: small-caps;
  text-align: center;
  background: #F2F7FE;
  padding: 10px 15px 3px 10px;
  margin-bottom: 1px;
  margin-right: 1px;
  border: 1px solid #7B899B;
}

.Toolbar button {
  padding: 6px;
  margin: 7px 2px;
  font-variant: normal;
  font-size: 12px;
}

.CanvasContainer {
  clear: both;
}

canvas {
  border: 1px solid #7B899B;
}

img {
  padding: 2px;
  border: 2px solid #F2F7FE;
}

img:hover {
  border: 2px groove #E4F0FE;
  background: white;
}


img.Selected {
  border: 2px groove #E4F0FE;
}

#savedCopyContainer {
  display: none;
}

#savedCopyContainer img {
  width: 250px;
  height: 125px;
}

2,将画布保存为图像
(1)调用<canvas>的 toDataURL() 方法,可以画布图像数据转换为字符序列并编码为数据URL。
var url = canvas.toDataURL(); 
(2)toDataURL()方法如果不提供参数,得到的将是一个PNG图片。如果想要其他格式的图片,可以传入相应的 MIME 类型。
var url = canvas.toDataURL("image/jpeg"); 
(3)数据URL就是一个以 data:image/png;base64 开头的 base-64 编码的字符串。
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA0AAAANCAYAAABy6%2BR8AAAAlElEQVR42oWQQRHEIAxF10ElVAISVgo3bCABCUhYCZWAhEpAQpoD6bzJhNnDO0DyyA8fEXkppXyVCpLViDUfyqVIQN9JFMY637hrlCySFauL21E7KVWbAIGx56rnSLqc5KPXSLo3kySalPhTygFhRDtFC09EIsMeZJSGBj7Qveh3OJW89syImiH%2BIO2BOJX0XwA2%2BQEL4pAhSX4aBQAAAABJRU5ErkJggg%3D%3D

(4)数据URL很适合传输图像,除了可以发送到Web服务器在后台保存下来,也可以作为<img>元素的src属性值显示出来。
// 找到预览的 <img> 元素标签
var imageCopy = document.getElementById("savedImageCopy");
// 将画布内容在img元素中显示
imageCopy.src = canvas.toDataURL();  
评论0