Trace a line on canvas using JavaScript
I am learning HTML5 and one of the examples that I want to learn is to create 2 points on a canvas and I should be able to trace a line between the 2 points and join them, this should be done both using mouse and touch events on the mobile devices.
Are there any 开发者_如何学运维frameworks that provide these API or are there any examples that I can look at to get started?
window.onload=function(){
var canvas = document.getElementById('canvas');
var ctx=canvas.getContext('2d');
var mouse={x:0,y:0}, down=false, lines=[]
canvas.addEventListener("mousedown",function(e) {
down=true
mouse={x:e.pageX,y:e.pageY}
},false);
canvas.addEventListener("mousemove",function(e) {
this.width=this.width
lines.map(function(item){
ctx.beginPath()
ctx.moveTo(item[0].x, item[0].y);
ctx.lineTo(item[1].x, item[1].y);
ctx.stroke();
})
if(down){
ctx.beginPath();
ctx.moveTo(mouse.x, mouse.y);
ctx.lineTo(e.pageX-this.offsetLeft, e.pageY-this.offsetTop);
ctx.stroke()
}
},false);
canvas.addEventListener("mouseup",function(e) {
down=false
this.width=this.width
lines.push([{x:mouse.x,y:mouse.y},{x:e.pageX-this.offsetLeft,y:e.pageY-this.offsetTop}])
lines.map(function(item){
ctx.beginPath()
ctx.moveTo(item[0].x, item[0].y);
ctx.lineTo(item[1].x, item[1].y);
ctx.stroke();
})
},false);
}
I made up a very basic snippet which might help you get started: http://jsfiddle.net/vF4dY/.
var ctx = $('canvas').get(0).getContext('2d');
$('canvas').mousedown(function(e) {
ctx.beginPath();
ctx.moveTo(e.offsetX, e.offsetY);
});
$('canvas').mouseup(function(e) {
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
});
精彩评论