I'm trying to create a drawing tool set for the iPad and so far I've done the square, but I'm not sure how I would go about coding a straight line ? Here's the code for my finished square, maybe it'll be a help. I would like to know how to code a straight line. After that, what if I wanted to draw circles as well? What in this code would I need to change?
Here's the code:
JavaScript (Square/Rectangle)
// "Draw Rectangle" Button
function rect(){
var canvas = document.getElementById('canvasSignature'), ctx = canvas.getContext('2d'), rect = {}, drag = false;
function init() {
canvas.addEventListener("touchstart", touchHandler, false);
canvas.addEventListener("touchmove", touchHandler, false);
canvas.addEventListener("touchend", touchHandler, false);
}
function touchHandler(event) {
if (event.targetTouches.length == 1) { //one finger touche
var touch = event.targetTouches[0];
if (event.type == "touchstart") {
rect.startX = touch.pageX;
rect.startY = touch.pageY;
drag = true;
} else if (event.type == "touchmove") {
if (drag) {
rect.w = touch.pageX - rect.startX;
rect.h = touch.pageY - rect.startY ;
draw();
}
} else if (event.type == "touchend" || event.type == "touchcancel") {
drag = false;
}
}
}
function draw() {
ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "orange";
}
init();
}
Just substitute this:
ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);
ctx.clearRect(0, 0, canvas.width, canvas.height);
with something like this:
ctx.fillLine(rect.startX, rect.startY, rect.w, rect.h);
ctx.clearLine(0, 0, canvas.width, canvas.height);
this is of course not 100% valid code, but the concept should work and you'll get the point
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.