您的位置:首页 > Web前端 > HTML5

Html5 Canvas一个简单的画笔例子

2015-04-22 01:24 567 查看
相比了下Qt quick的canvas和HTML5的canvas,发现HTML5 Canvas在同样绘制绘制操作下性能比Qt的canvas强很多,附上一个HTML5 canvas画笔一例子

var DW  = function( canvasid){
this._points = [];
this._canvas = document.getElementById( canvasid );
this._ctx = this._canvas.getContext("2d");
this._isPressed = false;
this._color  = "#223344";
this._widht = 8;

var self = this;

function __init(){
self._ctx.lineCap = "round";
self._ctx.lineJoin="round";
self._ctx.strokeStyle = self._color;
self._ctx.lineWidth = self._widht;
};

this._addPoints = function( x, y ){
this._points.push({x: x , y : y });
};

this._capturePath = function( x , y ){
this._addPoints( x,  y );
};

this._prepareDrawing = function( x, y ){
this._points.length = 0 ;
this._addPoints( x, y );
this._ctx.moveTo( x, y );
};

this._render = function(){
console.log("renderrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr");
var p1 = this._points[0] , p2 =this._points[1];
this._ctx.save();
this._ctx.beginPath();

if(this._points.length === 2 && p1.x === p2.x && p1.y===p2.y ){
p1.x -= 0.5 ;
p1.y -= 0.5 ;
}

this._ctx.moveTo( p1.x , p1.y );

for( var i = 1 , len = this._points.length ; i < len ; i++ ){
var mp = {x : (p1.x + (p2.x - p1.x ) /2) , y : (p1.y + (p2.y - p1.y)/2)};
this._ctx.quadraticCurveTo( p1.x , p1.y , mp.x , mp.y );
p1 = this._points[i] ; p2 = this._points[i+1];
}

this._ctx.lineTo( p1.x , p1.y );
this._ctx.stroke();
this._ctx.restore();
}

this._clearContext = function(){
this._ctx.clearRect(0,0, this._canvas.width , this._canvas.height);
}
__init();

};

DW.prototype.setColor = function(color){
this._color = color;
this._ctx.strokeStyle = color;
};

DW.prototype.setWidth = function( w ){
this._widht = w;
this._ctx.lineWidth = w ;
}


  

应用

<!doctype html>
<html>
<head>
<title> Canvas </title>
<style type="text/css">
canvas{
border-radius: 8;
border-style: solid;
border-color: 'gray'
}
</style>
<script ==> 引用上头JS文件 =========/script>
</head>
<body>
<canvas id="_canvas" width='500' height="400" ></canvas>
<script type="text/javascript">
var $ = function( id ){ return document.getElementById(id);}
var c = $('_canvas');
var dObject = new DW("_canvas");
function on_mouse_press(e){
dObject.setColor("#778899");
dObject._prepareDrawing(e.offsetX,e.offsetY);
dObject._capturePath(e.offsetX,e.offsetY);
dObject._render();

dObject._isPressed = true;
};

function on_mouse_move( e) {
if( dObject._isPressed === true ){
dObject._capturePath(e.offsetX,e.offsetY);
dObject._clearContext();
dObject._render(); //redraw
}
};

function on_mouse_up(e){
dObject._isPressed = false;
}

c.addEventListener('mousedown',function(e){
on_mouse_press(e);
},false);

c.addEventListener('mousemove' , function(e){
on_mouse_move(e);
},false);

c.addEventListener('mouseup',function(e){
on_mouse_up(e);
},false);
</script>
</body>
</html>


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: