2010年11月10日 星期三

Simple Canvas Demo

Below is js code:

$(function(){
var selectColor = 'red';
var canvas = document.getElementById('canvas')
var ctx = canvas.getContext('2d');
$('#canvas').mousedown(function(e){


ctx.strokeStyle = selectColor;
ctx.beginPath();
ctx.moveTo(e.clientX, e.clientY);
ctx.lineTo(e.clientX-1, e.clientY-1);
var px,py;
$('#canvas').bind('mousemove',function(e){

var x = px = e.clientX;
var y = py = e.clientY;

ctx.lineTo(x, y);
ctx.lineTo(x+2, y+2);
ctx.stroke();

$('#canvas').mouseup(function(e){
$('#canvas').unbind('mousemove');
ctx.lineTo(e.clientX, e.clientY);
ctx.lineTo(e.clientX+2, e.clientY+2);
});
});
})

$(document).mouseup(function(){
$('#canvas').unbind('mousemove');
});

var colors = ['#0000FF','#FFFF00','#00FF00','#FF0000','#FF91FE','#BE6100','#BCBE00','#5DBE00','#00BCBE'];
for(var i=0;i<10;i++){ class="tool" id="+i+">');
$('#'+i).css({'background-color':colors[i%colors.length]});
$('#'+i).click(function(){
$(this).addClass('toolactive');
selectColor = $(this).css('background-color');
}).mouseup(function(){
$(this).removeClass('toolactive');
});
}

$('#canvas').mouseover(function(e){
//tools.detect(e);
}).mousemove(function(e){
tools.detect(e);
}).mouseout(function(e){
$('#tools').mousemove(function(){
$('#tools').css({opacity:1});
}).mouseout(function(){
tools.hide();
});
tools.hide();
});
});




var tools ={
detect:function(e){
if(e.pageY>400){
this.show();
}else{
this.hide();
}
},
show:function(){
$('#tools').stop().animate({opacity:1},'slow',function(){
});
},
hide:function(){
$('#tools').stop().animate({opacity:0},'slow',function(){
});
}
}

Below is css code:

#canvas{
border:solid;
z-index:100;
}

.tool{
float:left;
padding:5px;
margin:5px;
width:50px;
height:30px;
background-color:#0000FF;
}

.toolactive{
background-color:#FF0000;
}

#tools{
background-color:#DDDDDD;
position:absolute;
bottom:25%;
left:15%;
float:left;
width:360px;
height:100px;
border:solid;
opacity:0;
}

Below is html code:






























Your browser should support canvas tag.
Demo link