Home > Article > Web Front-end > Introduction to how to use HTML5 to make a drawing board_html5 tutorial skills
The first thing to note is that you are not drawing with a mouse, but with your fingers on a touch device, such as an iPad.
To make a drawing board, naturally use HTML5 canvas to achieve it. In canvas we can draw circles, rectangles, custom lines, etc. This time I mainly use drawing circles and lines to achieve it. Response to touch events is supported in html.
onTouchStart Touch start
onTouchMove touch slide
onTouchEnd Touch end
With these events, it is very simple for us to draw with our fingers in the browser.
Effect on IPAD:
Idea: When the finger touches the screen, add a circle to the position where the finger touches in the onTouchStart event; when the finger starts to slide, continuously move from the previous touch point to the next in onTouchMove A dotted line.
HTML:
var ctx =canvas.getContext("2d");
ctx.lineWidth=10;//Brush thickness
ctx.strokeStyle="#FF0000";//Brush color
//Touch start event
function onTouchStart(event) {
event.preventDefault();
lastX=event.touches[0].clientX;
lastY=event.touches[ 0].clientY;
drawRound(lastX,lastY);
}
//Touch sliding event
function onTouchMove(event) {
try
{
event.preventDefault();
drawLine(lastX,lastY,event. touches[0].clientX,event.touches[0].clientY);
lastX=event.touches[0].clientX;
lastY=event.touches[0].clientY;
}
catch(err){
alert( err.description);
}
}
//Draw a circle
function drawRound(x,y)
{
ctx.fillStyle="#FF0000";
ctx.beginPath();
ctx.arc( x,y,5,0,Math.PI*2,true);
ctx.closePath();
ctx.fill();
}
//Draw line
function drawLine(startX,startY,endX,endY)
{
ctx.beginPath();
ctx.lineCap="round";
ctx.moveTo(startX,startY);
ctx .lineTo(endX,endY);
ctx.stroke();
}
Key points:
ctx.lineCap="round"; Set the style cap at the end of the drawn line to be round. This is very critical, otherwise there will be breaks in places where the angle of the line changes greatly.
event.preventDefault(); Cancel the default action of the event. This method must be called in the sliding event. Otherwise, the browser's default sliding event will be triggered when sliding, and the page will be pulled down, and you will not be able to draw.