HTML5的canvas元素是HTML5新特性中最有用的元素之一。通过html5 canvas,我们可以做图像处理、绘图、保存、恢复层和渲染图像等等操作,而不用依赖像Adobe Flash player和silverlight之类的外部插件。
在这篇文章中,我们将编写一个Javascript插件来使大家可以在canvas上随意涂写和绘画,就像一块涂鸦画板一样。另外再添加一些额外的小功能,如选择线条的宽度和颜色。
画板的最终效果就像下面这样,尝试在上面用鼠标画画看:
清空画板
Line width : 1
3
5
7
9
11
Color : black
blue
red
green
yellow
gray
HTML代码
我们需要一个用于绘画的canvas元素和一些用于选择操作的下拉框:
JAVASCRIPT
我们的涂鸦画板js脚本主要有三个函数:
InitThis():该方法用于初始化所需要的鼠标事件。
Draw():该方法在鼠标左键被按下时每次移动都会画一条线。
clearArea():该方法用于清空画板上的所有线条。
var mousePressed = false;
var lastX, lastY;
var ctx;
function InitThis() {
ctx = document.getElementById('myCanvas').getContext("2d");
$('#myCanvas').mousedown(function (e) {
mousePressed = true;
Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, false);
});
$('#myCanvas').mousemove(function (e) {
if (mousePressed) {
Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, true);
}
});
$('#myCanvas').mouseup(function (e) {
mousePressed = false;
});
$('#myCanvas').mouseleave(function (e) {
mousePressed = false;
});
}
function Draw(x, y, isDown) {
if (isDown) {
ctx.beginPath();
ctx.strokeStyle = $('#selColor').val();
ctx.lineWidth = $('#selWidth').val();
ctx.lineJoin = "round";
ctx.moveTo(lastX, lastY);
ctx.lineTo(x, y);
ctx.closePath();
ctx.stroke();
}
lastX = x; lastY = y;
}
function clearArea() {
// Use the identity matrix while clearing the canvas
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}
在页面加载完毕后调用InitThis(),canvas现在就是一块涂鸦画板了。快来试一试吧!
如需转载,请注明文章出处和来源网址:http://www.divcss5.com/html/h62586.shtml