网页画板制作
看了这么久的canvas,今天用canvas写了个网页画板。
画板可以选择颜色,画笔大小进行绘图,可以切换背景图片。
下面简单介绍制作过程
- 第一阶段定义一些变量
var canvas=document.getElementById("canvas");
var context=canvas.getContext("2d");
var Img;
var red = new Image();
var orange = new Image();
var yellow = new Image();
var green = new Image();
var blue = new Image();
var purple = new Image();
var white = new Image();
var paint = false;
var index;
var index2;
var arr = [];
var sizeArr = [];
var state = context.getImageData(0,0,canvas.width,canvas.height);
history.pushState(state,null);
将颜色push到arr数组中
arr.push(red,orange,yellow,green,blue,purple,white)
这里解释一下,之所以要用push方法,是因为red、orange等是定义的变量,如果直接把它们添加到数组中,数组会以为那是一些字符串。
- 定义绘图函数
function prepareCanvas() {
//加载颜色小图片
red.onload = function() { context.drawImage(red,70,145,10,10);
};
red.src = "img/red_pen.png";
orange.onload = function() { context.drawImage(orange,80,145,10,10);
};
orange.src = "img/orange_pen.png";
yellow.onload = function() { context.drawImage(yellow,90,145,10,10);
};
yellow.src = "img/yellow_pen.png";
green.onload = function() { context.drawImage(green,100,145,10,10);
};
green.src = "img/green_pen.png";
blue.onload = function() { context.drawImage(blue,110,145,10,10);
};
blue.src = "img/blue_pen.png";
purple.onload = function() { context.drawImage(purple,120,145,10,10);
};
purple.src = "img/purple_png.png";
white.onload = function() { context.drawImage(white,130,145,10,10);
};
white.src = "img/white.png";
//绘图的函数
function addClick(x,y,ft,img) {
paint = ft;
if(paint) {
context.drawImage(img,x,y,sizeArr[index2],sizeArr[index2]);
}
}
//鼠标动作事件
$('#canvas').mousedown(function(e){
Img = arr[index];
var sx = canvas.width/canvas.offsetWidth;
var sy = canvas.height/canvas.offsetHeight;
var x = sx*e.clientX - (Img.naturalWidth/2)-100;
var y = sy*e.clientY - Img.naturalHeight/2;
paint = true;
addClick(x,y,true,Img);
});
$('#canvas').mousemove(function(e){
if(paint==true){
Img = arr[index];
var sx = canvas.width/canvas.offsetWidth;
var sy = canvas.height/canvas.offsetHeight;
var x = sx*e.clientX - (Img.naturalWidth/2)-100;
var y = sy*e.clientY - Img.naturalHeight/2;
addClick(x,y,true,Img);
}
});
$('#canvas').mouseup(function(e){
paint = false;
});
console.log(sizeArr[index2]);
}
- 颜色、画笔大小、背景图选择
$("#color li").click(function(){
index = $("#color li").index(this);
prepareCanvas();
});
$("#size li").click(function() {
index2 = $("#size li").index(this);
sizeArr = [1,2,3];
})
$(".imgChange li").click(function() {
var index3 =$(".imgChange li").index(this);
var imgArr = ["img/bg1.jpg","img/bg2.jpg","img/bg3.jpg","img/bg4.jpg"];
console.log(imgArr[index3]);
$("#canvas").css("background-image",'url('+imgArr[index3]+')');
})
- 记录historyAPI
window.addEventListener("popstate",loadState,false);
function loadState(e) {
context.clearRect(0,0,canvas.width,canvas.height);
if (e.state) {
context.putImageData(e.state,0,0);
};
}
使用historyAPI的原意,我是想通过点击浏览器后退按钮可以返回到画最后一笔之前,点击前进可以显示画最后一笔之后,但是没有实现效果,也没有报错。
- 存在的问题
画笔的起始点不是鼠标点击的点,这个应该是我获取的尺寸出错,我会找到原因然后更新博客。
若到江南赶上春,千万和春住