draggable & resizable Div - javascript

I wrote my own draggable & resizable code,
var startX, startY, startWidth, startHeight;
var div = document.getElementById('div'),
x1 = 0,
y1 = 0,
x2 = 0,
y2 = 0;
var element;
function reCalc() {
var x3 = Math.min(x1, x2);
var x4 = Math.max(x1, x2);
var y3 = Math.min(y1, y2);
var y4 = Math.max(y1, y2);
div.style.left = x3 + 'px';
div.style.top = y3 + 'px';
div.style.width = x4 - x3 + 'px';
div.style.height = y4 - y3 + 'px';
}
$(document).on("mousedown", function (e) {
var target = $(event.target);
x1 = e.clientX;
y1 = e.clientY;
if (element && element.find('.resizer').is(target)) {
return;
}
if (element) {
element.remove();
}
div.hidden = 0;
x1 = e.clientX;
y1 = e.clientY;
reCalc();
});
$(document).on("mousemove", function (e) {
x2 = e.clientX;
y2 = e.clientY;
reCalc();
});
$(document).on("mouseup", function (e) {
div.hidden = 1;
var target = $(event.target);
if (element && element.find('.resizer').is(target)) {
return;
}
element = $("<div>");
element[0].style.left = div.style.left;
element[0].style.top = div.style.top;
element[0].style.width = div.style.width;
element[0].style.height = div.style.height;
var resizer = document.createElement('div');
resizer.className = 'resizer';
element.append(resizer);
resizer.addEventListener('mousedown', initDrag, false);
$("body").append(element.show());
element.on("mousedown", function () {
event.stopImmediatePropagation();
});
element.on("mouseup", function () {
event.stopImmediatePropagation();
});
});
function initDrag(e) {
startX = e.clientX;
startY = e.clientY;
startWidth = parseInt(document.defaultView.getComputedStyle(element[0]).width, 10);
startHeight = parseInt(document.defaultView.getComputedStyle(element[0]).height, 10);
document.documentElement.addEventListener('mousemove', doDrag, false);
document.documentElement.addEventListener('mouseup', stopDrag, false);
}
function doDrag(e) {
element[0].style.width = (startWidth + e.clientX - startX) + 'px';
element[0].style.height = (startHeight + e.clientY - startY) + 'px';
}
function stopDrag(e) {
document.documentElement.removeEventListener('mousemove', doDrag, false);
document.documentElement.removeEventListener('mouseup', stopDrag, false);
}
but when I resize, It does not handle mousedown event properly. It should stop drag when i mouse up
Any solution??
http://jsfiddle.net/Dipak1991/7d8f65b8/1/

There is no listener to invoke your stopDrag() function:
resizer.addEventListener('mousedown', initDrag, false);
// Add
resizer.addEventListener('mouseup', stopDrag, false);
JSFiddle

Related

Prevent setAttribute from running twice

I'm trying to snap an element below another element and make it stay put. The function is ok, but it runs every time I move it 10px. So it moves 10px even further each time..
function move_box() {
if(el.offsetLeft = 10){
console.log('moved the element 10px to the left!');
el.setAttribute('class', 'snap_in'); // class with css (transform: translateY(10px)
let not_called = false;
console.log(not_called);
} else if (not_called = false){
console.log(not_called);
el.setAttribute('class', 'dont_move'); //class with css transform:translateY(0px);
}
}
}
use '==' instead of =
you are assigning not comparing
const el = document.querySelector('.item');
let not_called;
el.addEventListener('mousedown', mousedown);
function mousedown(e){
window.addEventListener('mousemove', mousemove);
window.addEventListener('mouseup', mouseup);
let prevX = e.clientX;
let prevY = e.clientY;
function mousemove(e) {
let newX = prevX - e.clientX;
let newY = prevY - e.clientY;
const rect = el.getBoundingClientRect();
el.style.left = rect.left - newX + "px";
el.style.top = rect.top - newY + "px";
prevX = e.clientX;
prevY = e.clientY;
}
function mouseup() {
window.removeEventListener('mousemove', mousemove);
window.removeEventListener('mouseup', mouseup);
console.log(el.offsetLeft);
console.log(el.offsetTop);
//let leftoffset = el.offsetLeft;
if (not_called == false){
console.log(not_called);
el.setAttribute('class', 'item');
}
else if(el.offsetLeft >= 180 && el.offsetLeft <= 220){
console.log('yes!');
el.setAttribute('class', 'snap_in');
not_called = false;
console.log(not_called);
}
}
}

Can not drag objects in canvas when the latter is scrolled offscreen

I have taken a working jsFiddle with draggable battleships on a canvas and have just added some HTML paragraphs on top of it. Suddenly I can not drag the battleships anymore.
I have tried adding e.pageX and e.pageY in the mouse handlers, but that does not help.
How to handle scrolled content in such situations?
Please see a screenshot and the copy of the troubled JavaScript code below -
jQuery(document).ready(function($) {
var board = document.getElementById("board");
var ctx = board.getContext("2d");
ctx.strokeStyle = "lightgray";
var canvasOffset = $("#board").offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
console.log('ready: offsetX=' + offsetX + ", " + "offsetY=" + offsetY);
var mouseIsDown = false;
var lastX = 0;
var lastY = 0;
var ships = [];
makeShip(20, 30, 50, 25, "skyblue");
makeShip(20, 100, 30, 25, "skyblue");
makeShip(20, 170, 50, 25, "salmon");
makeShip(20, 240, 30, 25, "salmon");
function makeShip(x, y, width, height, fill) {
var ship = {
x: x,
y: y,
width: width,
height: height,
right: x + width,
bottom: y + height,
fill: fill
}
ships.push(ship);
}
drawAllShips();
function drawAllShips() {
ctx.clearRect(0, 0, board.width, board.height);
for (var i = 0; i < ships.length; i++) {
var ship = ships[i]
drawShip(ship);
ctx.fillStyle = ship.fill;
ctx.fill();
ctx.stroke();
}
}
function drawShip(ship) {
ctx.beginPath();
ctx.moveTo(ship.x, ship.y);
ctx.lineTo(ship.right, ship.y);
ctx.lineTo(ship.right + 10, ship.y + ship.height / 2);
ctx.lineTo(ship.right, ship.bottom);
ctx.lineTo(ship.x, ship.bottom);
ctx.closePath();
}
function handleMouseDown(e) {
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
console.log('handleMouseDown: mouseX=' + mouseX + ", " + "mouseY=" + mouseY);
lastX = mouseX;
lastY = mouseY;
mouseIsDown = true;
}
function handleMouseUp(e) {
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
console.log('handleMouseUp: mouseX=' + mouseX + ", " + "mouseY=" + mouseY);
mouseIsDown = false;
}
function handleMouseMove(e) {
if (!mouseIsDown) {
return;
}
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
console.log('handleMouseMove: mouseX=' + mouseX + ", " + "mouseY=" + mouseY);
for (var i = 0; i < ships.length; i++) {
var ship = ships[i];
drawShip(ship);
if (ctx.isPointInPath(lastX, lastY)) {
ship.x += (mouseX - lastX);
ship.y += (mouseY - lastY);
ship.right = ship.x + ship.width;
ship.bottom = ship.y + ship.height;
}
}
lastX = mouseX;
lastY = mouseY;
drawAllShips();
}
$("#board").mousedown(function(e) {
handleMouseDown(e);
});
$("#board").mousemove(function(e) {
handleMouseMove(e);
});
$("#board").mouseup(function(e) {
handleMouseUp(e);
});
});
You need also to consider the document scroll values
Here is the sample i created
jQuery(document).ready(function($) {
var board = document.getElementById("board");
var ctx = board.getContext("2d");
ctx.strokeStyle = "lightgray";
var canvasOffset = $("#board").offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var scrolltop = $(document).scrollTop();
var scrollleft = $(document).scrollLeft();
console.log('ready: offsetX=' + offsetX + ", " + "offsetY=" + offsetY, scrolltop, scrollleft);
var mouseIsDown = false;
var lastX = 0;
var lastY = 0;
var ships = [];
makeShip(20, 30, 50, 25, "skyblue");
makeShip(20, 100, 30, 25, "skyblue");
makeShip(20, 170, 50, 25, "salmon");
makeShip(20, 240, 30, 25, "salmon");
function makeShip(x, y, width, height, fill) {
var ship = {
x: x,
y: y,
width: width,
height: height,
right: x + width,
bottom: y + height,
fill: fill
}
ships.push(ship);
return (ship);
}
drawAllShips();
function drawAllShips() {
ctx.clearRect(0, 0, board.width, board.height);
for (var i = 0; i < ships.length; i++) {
var ship = ships[i]
drawShip(ship);
ctx.fillStyle = ship.fill;
ctx.fill();
ctx.stroke();
}
}
function drawShip(ship) {
ctx.beginPath();
ctx.moveTo(ship.x, ship.y);
ctx.lineTo(ship.right, ship.y);
ctx.lineTo(ship.right + 10, ship.y + ship.height / 2);
ctx.lineTo(ship.right, ship.bottom);
ctx.lineTo(ship.x, ship.bottom);
ctx.closePath();
}
function handleMouseDown(e) {
scrolltop = $(document).scrollTop();
scrollleft = $(document).scrollLeft();
mouseX = parseInt(e.clientX - offsetX + scrollleft);
mouseY = parseInt(e.clientY - offsetY + scrolltop);
lastX = mouseX;
lastY = mouseY;
mouseIsDown = true;
console.log('ready: offsetX=' + offsetX + ", " + "offsetY=" + offsetY, scrolltop, scrollleft);
}
function handleMouseUp(e) {
mouseX = parseInt(e.clientX - offsetX + scrollleft);
mouseY = parseInt(e.clientY - offsetY + scrolltop);
console.log('handleMouseUp: mouseX=' + mouseX + ", " + "mouseY=" + mouseY);
mouseIsDown = false;
}
function handleMouseMove(e) {
if (!mouseIsDown) {
return;
}
mouseX = parseInt(e.clientX - offsetX + scrollleft);
mouseY = parseInt(e.clientY - offsetY + scrolltop);
console.log('handleMouseMove: mouseX=' + mouseX + ", " + "mouseY=" + mouseY);
for (var i = 0; i < ships.length; i++) {
var ship = ships[i];
drawShip(ship);
if (ctx.isPointInPath(lastX, lastY)) {
ship.x += (mouseX - lastX);
ship.y += (mouseY - lastY);
ship.right = ship.x + ship.width;
ship.bottom = ship.y + ship.height;
}
}
lastX = mouseX;
lastY = mouseY;
drawAllShips();
}
$("#board").mousedown(function (e) {
handleMouseDown(e);
});
$("#board").mousemove(function (e) {
handleMouseMove(e);
});
$("#board").mouseup(function (e) {
handleMouseUp(e);
});
});
DEMO HERE

Capture user input on HTML canvas/Javascript and vice versa

I am trying to draw a rectangle in HTML5 canvas based on user input. I am also trying to do the opposite. If a user draws a rectangle in the canvas, the width and height values are dropped into the form. Please see my jsfiddle.
http://jsfiddle.net/hbrennan72/FyTx5/
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var rect = {};
//var drag = false;
function getarea()
{
var wid = document.getElementById("wid").value;
var hgt = document.getElementById("hgt").value;
var area = wid * hgt;
var perim = wid * 2 + hgt * 2;
if (wid =="") {
document.getElementById("errors").innerHTML = "The value for the width is blank.";
document.getElementById('wid').focus();
}
else if (hgt == "") {
document.getElementById("errors").innerHTML = "The value for the height is blank.";
document.getElementById("hgt").focus();
}
else if (isNaN (wid)) {
document.getElementById("errors").innerHTML = "Please enter a numeric value for the width.";
document.getElementById('wid').focus();
}
else if (isNaN (hgt)) {
document.getElementById("errors").innerHTML = "Please enter a numeric value for the height.";
document.getElementById("hgt").focus();
}
else if (wid <= 0) {
document.getElementById("errors").innerHTML = "The width is less than or equal to zero.";
document.getElementById('wid').focus();
}
else if (hgt <= 0) {
document.getElementById("errors").innerHTML = "The height is less than or equal to zero.";
document.getElementById("hgt").focus();
}
else if (wid > 500) {
document.getElementById("errors").innerHTML = "The width is greater than 500.";
document.getElementById('wid').focus();
}
else if (hgt > 500) {
document.getElementById("errors").innerHTML = "The height is greater than 500.";
document.getElementById("hgt").focus();
}
else {
window.document.getElementById("area").innerHTML = area;
window.document.getElementById("perim").innerHTML = perim;
document.getElementById("errors").innerHTML = "Please see results listed above.";
}
}
function updateform (){
"use strict"
var wid = document.getElementById("wid").value;
var hgt = document.getElementById("hgt").value;
var area = wid * hgt;
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2D");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillRect(0,0, rect.wid, rect.hgt);
context.fillStyle = "#FF0000"; //red color
draw();
}
function mouseDown(e)
{
rect.startX = e.pageX - this.offsetLeft;
rect.startY = e.pageY - this.offsetTop;
canvas.style.cursor="crosshair";
drag = true;
}
function mouseUp () {
drag = false;
}
function mouseMove(e) {
if (drag) {
rect.wid = (e.pageX - this.offsetLeft) - rect.startX;
rect.hgt = (e.pageY - this.offsetTop) - rect.startY ;
context.clearRect(0,0,canvas.width,canvas.height);
draw();
}
}
function init() {
canvas.addEventListener("mousedown", mouseDown, false);
canvas.addEventListener("mouseup", mouseUp, false);
canvas.addEventListener("mousemove", mouseMove, false);
}
init();
function drawform() {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2D");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillRect(0,0, rect.wid, rect.hgt);
context.fillStyle = "#FF0000"; //red color
}
function draw (){
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillRect(rect.startX, rect.startY, rect.wid, rect.hgt);
context.fillStyle = "#378E37"; //green color
}
draw();
I have tried to do it in this way.It is working fine.The code is
$("#smt").click(function(){
var canvasel=' <canvas id="myCanvas" width="400" height="400"></canvas>'
$("#canvas").append(canvasel)
var w=$("#wid").val();
var h=$("#hgt").val();
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.rect(20,20,w,h);
ctx.stroke();
})
$("#clr").click(function(){
$("#canvas").empty();
$("#wid").val('');
$("#hgt").val('');
})
initDraw(document.getElementById('canvas'));
function initDraw(canvas) {
function setMousePosition(e) {
var ev = e || window.event; //Moz || IE
if (ev.pageX) { //Moz
mouse.x = ev.pageX + window.pageXOffset;
mouse.y = ev.pageY + window.pageYOffset;
} else if (ev.clientX) { //IE
mouse.x = ev.clientX + document.body.scrollLeft;
mouse.y = ev.clientY + document.body.scrollTop;
}
};
var mouse = {
x: 0,
y: 0,
startX: 0,
startY: 0
};
var element = null;
canvas.onmousemove = function (e) {
setMousePosition();
if (element !== null) {
element.style.width = Math.abs(mouse.x - mouse.startX) + 'px';
element.style.height = Math.abs(mouse.y - mouse.startY) + 'px';
element.style.left = (mouse.x - mouse.startX < 0) ? mouse.x + 'px' : mouse.startX + 'px';
element.style.top = (mouse.y - mouse.startY < 0) ? mouse.y + 'px' : mouse.startY + 'px';
}
}
canvas.onclick = function (e) {
if (element !== null) {
element = null;
canvas.style.cursor = "default";
console.log("finsihed.");
var width=$(".rectangle").width();
var height=$(".rectangle").height();
$("#wid").val(width);
$("#hgt").val(height)
} else {
console.log("begun.");
mouse.startX = mouse.x;
mouse.startY = mouse.y;
element = document.createElement('div');
element.className = 'rectangle'
element.style.left = mouse.x + 'px';
element.style.top = mouse.y + 'px';
canvas.appendChild(element)
canvas.style.cursor = "crosshair";
}
}
}
SEE DEMO HERE
NOTE:Its not working in Mozilla. I am trying to fix it.Check in Chrome

Simple drag and drop code

Im struggling with seemingly a simple javascript exercise, writing a vanilla drag and drop. I think Im making a mistake with my 'addeventlisteners', here is the code:
var ele = document.getElementsByClassName ("target")[0];
var stateMouseDown = false;
//ele.onmousedown = eleMouseDown;
ele.addEventListener ("onmousedown" , eleMouseDown , false);
function eleMouseDown () {
stateMouseDown = true;
document.addEventListener ("onmousemove" , eleMouseMove , false);
}
function eleMouseMove (ev) {
do {
var pX = ev.pageX;
var pY = ev.pageY;
ele.style.left = pX + "px";
ele.style.top = pY + "px";
document.addEventListener ("onmouseup" , eleMouseUp , false);
} while (stateMouseDown === true);
}
function eleMouseUp () {
stateMouseDown = false;
document.removeEventListener ("onmousemove" , eleMouseMove , false);
document.removeEventListener ("onmouseup" , eleMouseUp , false);
}
Here's a jsfiddle with it working: http://jsfiddle.net/fpb7j/1/
There were 2 main issues, first being the use of onmousedown, onmousemove and onmouseup. I believe those are only to be used with attached events:
document.body.attachEvent('onmousemove',drag);
while mousedown, mousemove and mouseup are for event listeners:
document.body.addEventListener('mousemove',drag);
The second issue was the do-while loop in the move event function. That function's being called every time the mouse moves a pixel, so the loop isn't needed:
var ele = document.getElementsByClassName ("target")[0];
ele.addEventListener ("mousedown" , eleMouseDown , false);
function eleMouseDown () {
stateMouseDown = true;
document.addEventListener ("mousemove" , eleMouseMove , false);
}
function eleMouseMove (ev) {
var pX = ev.pageX;
var pY = ev.pageY;
ele.style.left = pX + "px";
ele.style.top = pY + "px";
document.addEventListener ("mouseup" , eleMouseUp , false);
}
function eleMouseUp () {
document.removeEventListener ("mousemove" , eleMouseMove , false);
document.removeEventListener ("mouseup" , eleMouseUp , false);
}
By the way, I had to make the target's position absolute for it to work.
you can try this fiddle too, http://jsfiddle.net/dennisbot/4AH5Z/
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>titulo de mi pagina</title>
<style>
#target {
width: 100px;
height: 100px;
background-color: #ffc;
border: 2px solid blue;
position: absolute;
}
</style>
<script>
window.onload = function() {
var el = document.getElementById('target');
var mover = false, x, y, posx, posy, first = true;
el.onmousedown = function() {
mover = true;
};
el.onmouseup = function() {
mover = false;
first = true;
};
el.onmousemove = function(e) {
if (mover) {
if (first) {
x = e.offsetX;
y = e.offsetY;
first = false;
}
posx = e.pageX - x;
posy = e.pageY - y;
this.style.left = posx + 'px';
this.style.top = posy + 'px';
}
};
}
</script>
</head>
<body>
<div id="target" style="left: 10px; top:20px"></div>
</body>
</html>
I've just made a simple drag.
It's a one liner usage, and it handles things like the offset of the mouse to the top left corner of the element, onDrag/onStop callbacks, and SVG elements dragging
Here is the code.
// simple drag
function sdrag(onDrag, onStop) {
var startX = 0;
var startY = 0;
var el = this;
var dragging = false;
function move(e) {
el.style.left = (e.pageX - startX ) + 'px';
el.style.top = (e.pageY - startY ) + 'px';
onDrag && onDrag(el, e.pageX, startX, e.pageY, startY);
}
function startDragging(e) {
if (e.currentTarget instanceof HTMLElement || e.currentTarget instanceof SVGElement) {
dragging = true;
var left = el.style.left ? parseInt(el.style.left) : 0;
var top = el.style.top ? parseInt(el.style.top) : 0;
startX = e.pageX - left;
startY = e.pageY - top;
window.addEventListener('mousemove', move);
}
else {
throw new Error("Your target must be an html element");
}
}
this.addEventListener('mousedown', startDragging);
window.addEventListener('mouseup', function (e) {
if (true === dragging) {
dragging = false;
window.removeEventListener('mousemove', move);
onStop && onStop(el, e.pageX, startX, e.pageY, startY);
}
});
}
Element.prototype.sdrag = sdrag;
and to use it:
document.getElementById('my_target').sdrag();
You can also use onDrag and onStop callbacks:
document.getElementById('my_target').sdrag(onDrag, onStop);
Check my repo here for more details:
https://github.com/lingtalfi/simpledrag
this is how I do it
var MOVE = {
startX: undefined,
startY: undefined,
item: null
};
function contentDiv(color, width, height) {
var result = document.createElement('div');
result.style.width = width + 'px';
result.style.height = height + 'px';
result.style.backgroundColor = color;
return result;
}
function movable(content) {
var outer = document.createElement('div');
var inner = document.createElement('div');
outer.style.position = 'relative';
inner.style.position = 'relative';
inner.style.cursor = 'move';
inner.style.zIndex = 1000;
outer.appendChild(inner);
inner.appendChild(content);
inner.addEventListener('mousedown', function(evt) {
MOVE.item = this;
MOVE.startX = evt.pageX;
MOVE.startY = evt.pageY;
})
return outer;
}
function bodyOnload() {
document.getElementById('td1').appendChild(movable(contentDiv('blue', 100, 100)));
document.getElementById('td2').appendChild(movable(contentDiv('red', 100, 100)));
document.addEventListener('mousemove', function(evt) {
if (!MOVE.item) return;
if (evt.which!==1){ return; }
var dx = evt.pageX - MOVE.startX;
var dy = evt.pageY - MOVE.startY;
MOVE.item.parentElement.style.left = dx + 'px';
MOVE.item.parentElement.style.top = dy + 'px';
});
document.addEventListener('mouseup', function(evt) {
if (!MOVE.item) return;
var dx = evt.pageX - MOVE.startX;
var dy = evt.pageY - MOVE.startY;
var sty = MOVE.item.style;
sty.left = (parseFloat(sty.left) || 0) + dx + 'px';
sty.top = (parseFloat(sty.top) || 0) + dy + 'px';
MOVE.item.parentElement.style.left = '';
MOVE.item.parentElement.style.top = '';
MOVE.item = null;
MOVE.startX = undefined;
MOVE.startY = undefined;
});
}
bodyOnload();
table {
user-select: none
}
<table>
<tr>
<td id='td1'></td>
<td id='td2'></td>
</tr>
</table>
While dragging, the left and right of the style of the parentElement of the dragged element are continuously updated. Then, on mouseup (='drop'), "the changes are committed", so to speak; we add the (horizontal and vertical) position changes (i.e., left and top) of the parent to the position of the element itself, and we clear left/top of the parent again. This way, we only need JavaScript variables for pageX, pageY (mouse position at drag start), while concerning the element position at drag start, we don't need JavaScript variables for that (just keeping that information in the DOM).
If you're dealing with SVG elements, you can use the same parent/child/commit technique. Just use two nested g, and use transform=translate(dx,dy) instead of style.left=dx, style.top=dy

Mouseactions vs touchevents in javascript

The topic may be insufficient to adress my question sorry for that because I am not so competent with the terms. The thing is I have a canvas and can draw things on that while I click mouse.. BUT when I try to do it with touching (i.e iphone and other touch operated devices) it did not detect the movements so no thing can be drawn on canvas..
What do I need to detect touch actions ? any ideas would be great..
here is my js fiddle link http://jsfiddle.net/regeme/xNSVm/
also here is the script for drawing
painting = false;
var WIDTH = 300;
var HEIGHT =300;
function clear() {
ctx.fillStyle = "black";
ctx.fillRect(0, 0, WIDTH, HEIGHT);
ctx.fillStyle = "white";
}
function generate(){
var newCanvas = document.createElement('canvas');
newCanvas.width = WIDTH;
newCanvas.height = HEIGHT;
document.getElementById('container').appendChild(newCanvas);
ctx = newCanvas.getContext('2d');
ctx.fillStyle = "black";
ctx.fillRect(0, 0, WIDTH, HEIGHT);
ctx.fillStyle = "white";
newCanvas.onmousedown = function(e) {
painting = true;
ctx = newCanvas.getContext('2d');
lastX = e.pageX - this.offsetLeft;
lastY = e.pageY - this.offsetTop;
};
newCanvas.onmouseup = function(e) {
painting = false;
};
newCanvas.onmousemove = function(e) {
if (painting) {
mouseX = e.pageX - this.offsetLeft;
mouseY = e.pageY - this.offsetTop;
// find all points between
var x1 = mouseX,
x2 = lastX,
y1 = mouseY,
y2 = lastY;
var steep = (Math.abs(y2 - y1) > Math.abs(x2 - x1));
if (steep){
var x = x1;
x1 = y1;
y1 = x;
var y = y2;
y2 = x2;
x2 = y;
}
if (x1 > x2) {
var x = x1;
x1 = x2;
x2 = x;
var y = y1;
y1 = y2;
y2 = y;
}
var dx = x2 - x1,
dy = Math.abs(y2 - y1),
error = 0,
de = dy / dx,
yStep = -1,
y = y1;
if (y1 < y2) {
yStep = 1;
}
for (var x = x1; x < x2; x++) {
if (steep) {
ctx.fillRect(y, x, 1, 1);
} else {
ctx.fillRect(x, y, 1, 1);
}
error += de;
if (error >= 0.5) {
y += yStep;
error -= 1.0;
}
}
lastX = mouseX;
lastY = mouseY;
}
};
}
document.getElementById('button').onclick = clear;
document.getElementById('generate').onclick = generate;
document.onmouseup = function(e) {
painting = false;
};
generate();
I can't comment or I would just leave this link in a comment. http://jsfiddle.net/gfcarv/66nVn/
However, since I am here I can kind of (emphasis on kind of) what is going on in the code.
This is the part where the touch events or the mouse events are attached:
// detect touch capabilities
var touchAvailable = ('createTouch' in document) || ('ontouchstart' in window);
// attach the touchstart, touchmove, touchend event listeners.
if(touchAvailable){
canvas.addEventListener('touchstart', draw, false);
canvas.addEventListener('touchmove', draw, false);
canvas.addEventListener('touchend', draw, false);
}
// attach the mousedown, mousemove, mouseup event listeners.
else {
canvas.addEventListener('mousedown', draw, false);
canvas.addEventListener('mousemove', draw, false);
canvas.addEventListener('mouseup', draw, false);
}
and this is the drawer function, it is basically using a switch statement to perform the correct calculations on the correct event that is happening
// create a drawer which tracks touch movements
var drawer = {
isDrawing: false,
touchstart: function (coors) {
context.beginPath();
context.moveTo(coors.x, coors.y);
this.isDrawing = true;
},
touchmove: function (coors) {
if (this.isDrawing) {
context.lineTo(coors.x, coors.y);
context.stroke();
}
},
touchend: function (coors) {
if (this.isDrawing) {
this.touchmove(coors);
this.isDrawing = false;
}
}
};
// create a function to pass touch events and coordinates to drawer
function draw(event) {
var type = null;
// map mouse events to touch events
switch(event.type){
case "mousedown":
event.touches = [];
event.touches[0] = {
pageX: event.pageX,
pageY: event.pageY
};
type = "touchstart";
break;
case "mousemove":
event.touches = [];
event.touches[0] = {
pageX: event.pageX,
pageY: event.pageY
};
type = "touchmove";
break;
case "mouseup":
event.touches = [];
event.touches[0] = {
pageX: event.pageX,
pageY: event.pageY
};
type = "touchend";
break;
}
// touchend clear the touches[0], so we need to use changedTouches[0]
var coors;
if(event.type === "touchend") {
coors = {
x: event.changedTouches[0].pageX,
y: event.changedTouches[0].pageY
};
}
else {
// get the touch coordinates
coors = {
x: event.touches[0].pageX,
y: event.touches[0].pageY
};
}
type = type || event.type
// pass the coordinates to the appropriate handler
drawer[type](coors);
}
I would break those down and study that fiddle, then you should be able to either rework your code or just add-in the correct events. I would rework if possible just b/c the functions seem a little cleaner in this context.
If I have time tomorrow I will edit with some more info if needed just figured this would help you get started. Thanks!
you should use "touch" events , such as ouchstart,touchend,touchmove, here is a paper about touch events , hopes it will help you
http://www.html5rocks.com/en/mobile/touch/

Categories

Resources