Trying to make this script work with touchscreen - html

i got this code looking around this forum but, I'm not being able to make it work on mobile devices with touchscreen. Problem is I need it to work as simple as this, not calling any library, because it's not for an app but for a simple Wordpress that's using an html widget. Is this even posible?
Thank you all!
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="400" height="200" style="background: #ffffff; margin-left: 0px;">Your browser does not support the HTML5 canvas tag.</canvas>
<script>
const c = document.getElementById("myCanvas");
// c.addEventListener("click", penTool); // fires after mouse left btn is released
c.addEventListener("mousedown", setLastCoords); // fires before mouse left btn is released
c.addEventListener("mousemove", freeForm);
const ctx = c.getContext("2d");
function setLastCoords(e) {
const {x, y} = c.getBoundingClientRect();
lastX = e.clientX - x;
lastY = e.clientY - y;
}
function freeForm(e) {
if (e.buttons !== 1) return; // left button is not pushed yet
penTool(e);
}
function penTool(e) {
const {x, y} = c.getBoundingClientRect();
const newX = e.clientX - x;
const newY = e.clientY - y;
ctx.beginPath();
ctx.lineWidth = 5;
ctx.moveTo(lastX, lastY);
ctx.lineTo(newX, newY);
ctx.strokeStyle = 'black';
ctx.stroke();
ctx.closePath();
lastX = newX;
lastY = newY;
}
let lastX = 0;
let lastY = 0;
</script>
</body>
</html>
Came up with this for mobile version only, still not working :(
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="400" height="200" style="background: #ffffff; margin-left: 0px;">Your browser does not support the HTML5 canvas tag.</canvas>
<script>
const c = document.getElementById("myCanvas");
// c.addEventListener("click", penTool); // fires after mouse left btn is released
c.addEventListener("touchstart", setLastCoords); // fires before mouse left btn is released
c.addEventListener("touchmove", freeForm);
const ctx = c.getContext("2d");
function setLastCoords(e) {
const {x, y} = c.getBoundingClientRect();
lastX = e.touches[0].clientX - x;
lastY = e.touches[0].clientY - y;
}
function freeForm(e) {
if (e.touches !== 1) return; // left button is not pushed yet
penTool(e);
}
function penTool(e) {
const {x, y} = c.getBoundingClientRect();
const newX = e.touches[0].clientX;
const newY = e.touches[0].clientY;
ctx.beginPath();
ctx.lineWidth = 5;
ctx.moveTo(lastX, lastY);
ctx.lineTo(newX, newY);
ctx.strokeStyle = 'black';
ctx.stroke();
ctx.closePath();
lastX = newX;
lastY = newY;
}
let lastX = 0;
let lastY = 0;
</script>
</body>
</html>
I also tried this script (credits to Zipso, great article on that)
<head>
<title>Sketchpad</title>
<script type="text/javascript">
// Variables for referencing the canvas and 2dcanvas context
var canvas,ctx;
// Variables to keep track of the mouse position and left-button status
var mouseX,mouseY,mouseDown=0;
// Variables to keep track of the touch position
var touchX,touchY;
// Keep track of the old/last position when drawing a line
// We set it to -1 at the start to indicate that we don't have a good value for it yet
var lastX,lastY=-1;
// Draws a line between the specified position on the supplied canvas name
// Parameters are: A canvas context, the x position, the y position, the size of the dot
function drawLine(ctx,x,y,size) {
// If lastX is not set, set lastX and lastY to the current position
if (lastX==-1) {
lastX=x;
lastY=y;
}
// Let's use black by setting RGB values to 0, and 255 alpha (completely opaque)
r=0; g=0; b=0; a=255;
// Select a fill style
ctx.strokeStyle = "rgba("+r+","+g+","+b+","+(a/255)+")";
// Set the line "cap" style to round, so lines at different angles can join into each other
ctx.lineCap = "round";
//ctx.lineJoin = "round";
// Draw a filled line
ctx.beginPath();
// First, move to the old (previous) position
ctx.moveTo(lastX,lastY);
// Now draw a line to the current touch/pointer position
ctx.lineTo(x,y);
// Set the line thickness and draw the line
ctx.lineWidth = size;
ctx.stroke();
ctx.closePath();
// Update the last position to reference the current position
lastX=x;
lastY=y;
}
// Clear the canvas context using the canvas width and height
function clearCanvas(canvas,ctx) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
// Keep track of the mouse button being pressed and draw a dot at current location
function sketchpad_mouseDown() {
mouseDown=1;
drawLine(ctx,mouseX,mouseY,12);
}
// Keep track of the mouse button being released
function sketchpad_mouseUp() {
mouseDown=0;
// Reset lastX and lastY to -1 to indicate that they are now invalid, since we have lifted the "pen"
lastX=-1;
lastY=-1;
}
// Keep track of the mouse position and draw a dot if mouse button is currently pressed
function sketchpad_mouseMove(e) {
// Update the mouse co-ordinates when moved
getMousePos(e);
// Draw a dot if the mouse button is currently being pressed
if (mouseDown==1) {
drawLine(ctx,mouseX,mouseY,12);
}
}
// Get the current mouse position relative to the top-left of the canvas
function getMousePos(e) {
if (!e)
var e = event;
if (e.offsetX) {
mouseX = e.offsetX;
mouseY = e.offsetY;
}
else if (e.layerX) {
mouseX = e.layerX;
mouseY = e.layerY;
}
}
// Draw something when a touch start is detected
function sketchpad_touchStart() {
// Update the touch co-ordinates
getTouchPos();
drawLine(ctx,touchX,touchY,12);
// Prevents an additional mousedown event being triggered
event.preventDefault();
}
function sketchpad_touchEnd() {
// Reset lastX and lastY to -1 to indicate that they are now invalid, since we have lifted the "pen"
lastX=-1;
lastY=-1;
}
// Draw something and prevent the default scrolling when touch movement is detected
function sketchpad_touchMove(e) {
// Update the touch co-ordinates
getTouchPos(e);
// During a touchmove event, unlike a mousemove event, we don't need to check if the touch is engaged, since there will always be contact with the screen by definition.
drawLine(ctx,touchX,touchY,12);
// Prevent a scrolling action as a result of this touchmove triggering.
event.preventDefault();
}
// Get the touch position relative to the top-left of the canvas
// When we get the raw values of pageX and pageY below, they take into account the scrolling on the page
// but not the position relative to our target div. We'll adjust them using "target.offsetLeft" and
// "target.offsetTop" to get the correct values in relation to the top left of the canvas.
function getTouchPos(e) {
if (!e)
var e = event;
if(e.touches) {
if (e.touches.length == 1) { // Only deal with one finger
var touch = e.touches[0]; // Get the information for finger #1
touchX=touch.pageX-touch.target.offsetLeft;
touchY=touch.pageY-touch.target.offsetTop;
}
}
}
// Set-up the canvas and add our event handlers after the page has loaded
function init() {
// Get the specific canvas element from the HTML document
canvas = document.getElementById('sketchpad');
// If the browser supports the canvas tag, get the 2d drawing context for this canvas
if (canvas.getContext)
ctx = canvas.getContext('2d');
// Check that we have a valid context to draw on/with before adding event handlers
if (ctx) {
// React to mouse events on the canvas, and mouseup on the entire document
canvas.addEventListener('mousedown', sketchpad_mouseDown, false);
canvas.addEventListener('mousemove', sketchpad_mouseMove, false);
window.addEventListener('mouseup', sketchpad_mouseUp, false);
// React to touch events on the canvas
canvas.addEventListener('touchstart', sketchpad_touchStart, false);
canvas.addEventListener('touchend', sketchpad_touchEnd, false);
canvas.addEventListener('touchmove', sketchpad_touchMove, false);
}
}
</script>
<style>
/* Some CSS styling */
#sketchpadapp {
/* Prevent nearby text being highlighted when accidentally dragging mouse outside confines of the canvas */
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.leftside {
float:left;
width:220px;
height:285px;
background-color:#def;
padding:10px;
border-radius:4px;
}
.rightside {
float:left;
margin-left:10px;
}
#sketchpad {
float:left;
height:300px;
width:400px;
border:2px solid #888;
border-radius:4px;
position:relative; /* Necessary for correct mouse co-ords in Firefox */
}
#clearbutton {
font-size: 15px;
padding: 10px;
-webkit-appearance: none;
background: #eee;
border: 1px solid #888;
}
</style>
</head>
<body onload="init()">
<div id="sketchpadapp">
<div class="leftside">
Touchscreen and mouse support HTML5 canvas sketchpad.<br/><br/>
Draw something by tapping or dragging.<br/><br/>
Works on iOS, Android and desktop/laptop touchscreens using Chrome/Firefox/Safari.<br/><br/>
<input type="submit" value="Clear Sketchpad" id="clearbutton" onclick="clearCanvas(canvas,ctx);">
</div>
<div class="rightside">
<canvas id="sketchpad" height="300" width="400">
</canvas>
</div>
</div>
</body>
</html>
But I can't manage to make it work on my mobile, as it only draws the first dot when touching!

Related

Canvas animation using png file

I am trying to make a racing game using canvas, and a png file with transparent background for the car.
I have a problem when I hold down on one of the arrows. In the opposite way of the movement it appears like a white shadow the old position of the car.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var canvas;
var ctx;
var car = new Image();
var x = 0;
var y = 0;
function startUp(){
canvas = document.getElementById('myCanvas');
ctx = canvas.getContext('2d');
loadImages();
startGameLoop();
}
function startGameLoop() {
setInterval(function() {
drawScreen();
drawCar();
}, 16);
window.addEventListener('keydown', whatKey, true);
}
function drawScreen(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#aaaaaa';
ctx.rect(0, 0, canvas.width, canvas.height);
ctx.fill();
}
function drawCar(){
ctx.drawImage(car, x ,y, 200, 103);
}
function whatKey(evt) {
switch (evt.keyCode) {
// Left arrow.
case 37: {
x -= 15;
}
break;
// Right arrow.
case 39:{
x += 15;
}
break;
// Down arrow
case 40:{
y += 15;
}
break;
// Up arrow
case 38: {
y -= 15;
}
break;
}
}
function loadImages() {
car.src = 'http://sammywasem.com/images/f3-top.png';
}
</script>
</head>
<body onload="startUp()">
<canvas id="myCanvas" width="1050" height="620">
</canvas>
</body>
</html>
The car move is in fact the right way.
Say you press the right key : the event is sent to the window, and trapped by your code : the car goes right. But the event is also handled by the whole window, where it is understood as : move the window to the right.
So what you see in the end, since the window move more than the car, is a move to the left of the car.
What you need to do is to prevent the key event from bubbling further once you handled it : it is done with
event.preventDefault();
and
event.stopPropagation();
look mdn to see the specifications of preventDefault or stopPropagation .
i've done a fiddle out of your code, and updated it :
http://jsbin.com/joboxuvu/1/edit?js,output

is mouse in user drawn area on canvas

Basically, a user uploads a picture and then can paint on it, and save the result. Another user can then view the photo and if they click in the same area as painted, something happens.
So user 1 can make an area click-able for user 2 by drawing on the photo.
now the upload bit is fine, and painting with help from a tutorial and example I've got sussed out. But defining what area is click-able is a bit harder. For something like a rectangle its easy enough, I made an example.
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var button = new Object();
button.x = 50;
button.y = 50;
button.width = 50;
button.height = 50;
button.rgb = "rgb(0, 0, 255)";
function drawbutton(buttonobject)
{
context.fillStyle = buttonobject.rgb;
context.fillRect (buttonobject.x, buttonobject.y, buttonobject.width, buttonobject.height);
context.strokeRect(buttonobject.x, buttonobject.y, buttonobject.width, buttonobject.height);
}
drawbutton(button);
function checkIfInsideButtonCoordinates(buttonObj, mouseX, mouseY)
{
if(((mouseX > buttonObj.x) && (mouseX < (buttonObj.x + buttonObj.width))) && ((mouseY > buttonObj.y) && (mouseY < (buttonObj.y + buttonObj.height))))
return true;
else
return false;
}
$("#myCanvas").click(function(eventObject) {
mouseX = eventObject.pageX - this.offsetLeft;
mouseY = eventObject.pageY - this.offsetTop;
if(checkIfInsideButtonCoordinates(button, mouseX, mouseY))
{
button.rgb = "rgb(0, 255, 0)";
drawbutton(button);
} else {
button.rgb = "rgb(255, 0, 0)";
drawbutton(button);
}
});
but when it comes to other shapes like circles, or just someone smothering the page, how would you go about detecting that ?
one thought I had was using the edited layer, making it hidden, and detecting a pixel color of say blue, from here but that limits the color use of the photo and im not entirely sure how to implement it. any other ideas ?
EDIT:
I figured out circles after some tinkering, using Pythagoras theorem to see if mouse coordinates are smaller than the radius, but this assumes circle center of 0,0, so then offset mouse by circles actual center. example
function checkIfInsideButtonCoordinates(buttonObj, mouseX, mouseY) {
actualX = mouseX - buttonObj.x
actualY = mouseY - buttonObj.y
mousesqX = actualX * actualX
mousesqY = actualY * actualY
sqR = buttonObj.r * buttonObj.r
sqC = mousesqX + mousesqY
if (sqC < sqR) return true;
else return false;
}
Here’s how to test whether user#2 is inside user#1’s paintings
Create a second canvas used to hit-test whether user#2 is inside of user#1’s paintings.
The hit-test canvas is the same size as the drawing canvas, but it only contains user#1’s paintings…not the image.
When user#1 is painting, also draw their paintings on the hit canvas.
When user#1 is done painting, save all their paintings from the hit canvas.
You have at least 2 ways to save user#1’s paintings from the hit canvas:
Serialize all the canvas commands needed to recreate the shapes/paths that user#1 paints.
Save the hit canvas as an image using canvas.toDataURL.
When user#2 clicks, check if the corresponding pixel on the hit canvas is filled or is transparent (alpha>0).
// getImageData for the hit-test canvas (this canvas just contains user#1's paintings)
imageDataData=hitCtx.getImageData(0,0,hit.width,hit.height).data;
// look at the pixel under user#2's mouse
// return true if that pixel is filled (not transparent)
function isHit(x,y){
var pixPos=(x+y*hitWidth)*4+3;
return( imageDataData[pixPos]>10)
}
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/etA5a/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; padding:15px; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var hit=document.getElementById("hit");
var hitCtx=hit.getContext("2d");
var user2=document.getElementById("user2");
var ctx2=user2.getContext("2d");
var canvasOffset=$("#user2").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var imageDataData;
var hitWidth=hit.width;
var img=document.createElement("img");
img.onload=function(){
// left canvas: image+user#1 paintings
ctx.globalAlpha=.25;
ctx.drawImage(img,0,0);
ctx.globalAlpha=1.00;
scribble(ctx,"black");
// mid canvas: just user#1 paintings (used for hittests)
scribble(hitCtx,"black");
// right canvas: user#2
ctx2.drawImage(img,0,0);
imageDataData=hitCtx.getImageData(0,0,hit.width,hit.height).data;
}
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/colorhouse.png";
function scribble(context,color){
context.beginPath();
context.moveTo(70,2);
context.lineTo(139,41);
context.lineTo(70,41);
context.closePath();
context.rect(39,54,22,30);
context.arc(73,115,3,0,Math.PI*2,false);
context.fillStyle=color;
context.fill();
}
function handleMouseMove(e){
var mouseX=parseInt(e.clientX-offsetX);
var mouseY=parseInt(e.clientY-offsetY);
// If user#2 has a hit on user#1's painting, mid-canvas turns red
var color="black";
if(isHit(mouseX,mouseY)){ color="red"; }
scribble(hitCtx,color);
}
function isHit(x,y){
var pixPos=(x+y*hitWidth)*4+3;
return( imageDataData[pixPos]>10)
}
$("#user2").mousemove(function(e){handleMouseMove(e);});
}); // end $(function(){});
</script>
</head>
<body>
<p>Left: original image with user#1 painting</p>
<p>Mid: user#1 painting only (used for hit-testing)</p>
<p>Right: user#2 (move mouse over hit areas)</p>
<canvas id="canvas" width=140 height=140></canvas>
<canvas id="hit" width=140 height=140></canvas>
<canvas id="user2" width=140 height=140></canvas><br>
</body>
</html>

drag and drop multiple images from one canvas to other

How do I drag and drop multiple images from one canvas to another? My manager has given me this task, it's been 3 days and I am not able to do this as I'm new to HTML5. I've searched Google but only got it working for one image. Please help me in this matter.
This is what I got for one image:
<pre>
<script>
window.onload = function ()
{
var canvas1 = document.getElementById("cvs1");
var canvas2 = document.getElementById("cvs2");
var context1 = canvas1.getContext('2d');
var context2 = canvas2.getContext('2d');
var imageXY = {x: 5, y: 5};
/**
* This draws the image to the canvas
*/
function Draw ()
{
//Clear both canvas first
context1.clearRect(0,0,canvas1.width,canvas1.height);
context2.clearRect(0,0,canvas2.width,canvas2.height);
//Draw a red rectangle around the image
if (state && state.dragging) {
state.canvas.getContext('2d').strokeStyle = 'red';
state.canvas.getContext('2d').strokeRect(imageXY.x - 2.5,
imageXY.y - 2.5,
state.image.width + 5,
state.image.height + 5);
}
// Now draw the image
state.canvas.getContext('2d').drawImage(state.image, imageXY.x, imageXY.y);
}
canvas2.onclick =
canvas1.onclick = function (e)
{
if (state && state.dragging) {
state.dragging = false;
Draw();
return;
}
var mouseXY = RGraph.getMouseXY(e);
state.canvas = e.target;
if ( mouseXY[0] > imageXY.x
&& mouseXY[0] < (imageXY.x + state.image.width)
&& mouseXY[1] > imageXY.y
&& mouseXY[1] < (imageXY.y + state.image.height)) {
state.dragging = true;
state.originalMouseX = mouseXY[0];
state.originalMouseY = mouseXY[1];
state.offsetX = mouseXY[0] - imageXY.x;
state.offsetY = mouseXY[1] - imageXY.y;
}
}
canvas1.onmousemove =
canvas2.onmousemove = function (e)
{
if (state.dragging) {
state.canvas = e.target;
var mouseXY = RGraph.getMouseXY(e);
// Work how far the mouse has moved since the mousedon event was triggered
var diffX = mouseXY[0] - state.originalMouseX;
var diffY = mouseXY[1] - state.originalMouseY;
imageXY.x = state.originalMouseX + diffX - state.offsetX;
imageXY.y = state.originalMouseY + diffY - state.offsetY;
Draw();
e.stopPropagation();
}
}
/**
* Load the image on canvas1 initially and set the state up with some defaults
*/
state = {}
state.dragging = false;
state.canvas = document.getElementById("cvs1");
state.image = new Image();
state.image.src = 'images/logo.png';
state.offsetX = 0;
state.offsetY = 0;
state.image.onload = function ()
{
Draw();
}
}
</script>
<canvas id="cvs1" width="400" height="125" style="float: left">[No canvas support]</canvas>
<canvas id="cvs2" width="400" height="125" style="float: left; margin-left: 100px">[No canvas support]</canvas>
</pre>
Drag/Drop multiple items between 2 canvases
Here’s what the code does:
Click to select one or more images from the top source canvas
Click an image again to toggle its selection on/off
Once you have made all your selections, drag from the top canvas to the bottom canvas
Your selections will be moved to the bottom canvas
Some explanation about the code:
Each image is stored in an array called Images
An item-object for each image is stored in an array called items
The item-object contains an item’s description, image-url, an isSelected flag and an isDropped flag.
The mouseup event handler of the top source canvas checks for hits on images and toggles their isSelected flags.
The mouseup event handler responds to drops onto the bottom drop canvas. It checks for selected items and records them as dropped by setting their isDropped flags.
The drawContainer function distributes items between the source and drop canvas based on their isDropped flags (isDropped==false are drawn in the top source canvas – isDropped==true are drawn in the bottom drop canvas)
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/3KqgX/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; padding:10px; }
canvas{border:1px solid red;}
#canvas {
}
#canvas:active {
cursor: move;
}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var drop=document.getElementById("dropzone");
var dropCtx=drop.getContext("2d");
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var mouseIsDown=false;
var frameWidth=128;
var frameHeight=128;
// checkmark for selected
var checkmark=document.createElement("img");
checkmark.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/smallCheckmark.png";
var images=[];
var items=[];
items.push({description:"House#1",url:"https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house1.jpg",isSelected:false,isDropped:false,x:0,y:0});
items.push({description:"House#2",url:"https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house2.jpg",isSelected:false,isDropped:false,x:0,y:0});
items.push({description:"House#3",url:"https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house3.jpg",isSelected:false,isDropped:false,x:0,y:0});
var imgLoadCount=0;
for(var i=0;i<items.length;i++){
images[i]=document.createElement("img");
images[i].onload=function(){
if(++imgLoadCount>=items.length){ draw(); }
}
images[i].src=items[i].url;
}
function draw(){
ctx.clearRect(0,0,canvas.width,canvas.height);
dropCtx.clearRect(0,0,drop.width,drop.height);
var canvasX=0;
var dropX=0;
//
for(var i=0;i<items.length;i++){
if(items[i].isDropped){
x=dropX*160+10;
drawContainer(dropCtx,i,x,20);
dropX++;
items[i].x=x;
}else{
x=canvasX*160+10;
drawContainer(ctx,i,x,20);
canvasX++;
items[i].x=x;
}
}
}
// draw image container
function drawContainer(context,index,x,y){
context.beginPath();
context.rect(x,y+frameHeight,frameWidth,30);
context.fillStyle="black";
context.fill();
context.beginPath();
context.fillStyle="white";
context.font="10pt Verdana";
context.fillText(items[index].description,x+10,y+frameHeight+18);
// draw a thumbnail of the image
var img=images[index];
if(img.width>=img.height){
context.drawImage(img,0,0,img.width,img.height,
x,y,128,128*img.height/img.width);
}else{
context.drawImage(img,0,0,img.width,img.height,
x,y,128*img.width/img.height,128); // edited s/b [,128], not [/128]
}
// outer frame (green if selected)
context.beginPath();
context.rect(x-2,y-2,frameWidth+4,frameHeight+30+4);
context.lineWidth=3;
context.strokeStyle="lightgray";
if(items[index].isSelected){
context.strokeStyle="green";
context.drawImage(checkmark,x+frameWidth-30,y+frameHeight+3);
}
context.stroke();
}
function handleMouseDown(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// Put your mousedown stuff here
mouseIsDown=true;
}
function handleMouseUp(e){
mouseIsDown=false;
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// Put your mouseup stuff here
for(var i=0;i<items.length;i++){
var item=items[i];
// have we clicked on something?
if(!item.isDropped && mouseX>=item.x && mouseX<=item.x+frameWidth){
// if so, toggle its selection
items[i].isSelected=!(items[i].isSelected);
draw();
}
}
}
function handleMouseOut(e){
if(!mouseIsDown){return;}
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// Put your mouseOut stuff here
}
function handleMouseMove(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// Put your mousemove stuff here
}
function handleDrop(e){
for(var i=0;i<items.length;i++){
if(items[i].isSelected){
items[i].isDropped=true;
items[i].isSelected=false;
console.log(i);
}
}
draw();
}
$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mousemove(function(e){handleMouseMove(e);});
$("#canvas").mouseup(function(e){handleMouseUp(e);});
$("#canvas").mouseout(function(e){handleMouseOut(e);});
$("#dropzone").mouseup(function(e){handleDrop(e);});
}); // end $(function(){});
</script>
</head>
<body>
<p>Click an item to toggle it's selection</p>
<p>Drag from top to bottom canvas to drop selected items</p>
<canvas id="canvas" width=500 height=200></canvas><br>
<canvas id="dropzone" width=500 height=200></canvas>
</body>
</html>
[Addition: Alternate code to sort bottom canvas by order dropped]
function handleDrop(e){
for(var i=items.length-1;i>=0;i--){
if(items[i].isSelected){
items[i].isDropped=true;
items[i].isSelected=false;
// sort the bottom canvas by order dropped
var move=items[i];
items.splice(i,1);
items.push(move);
}
}
draw();
}
[ Edited to present a solution in KineticJS ]
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/bSpBF/
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.5.1.min.js"></script>
<style>
body{ background-color: ivory; padding:10px;}
#container1,#container2{
border:solid 1px #ccc;
margin-top: 10px;
width:300px;
height:100px;
}
#container2{
height:300px;
}
</style>
<script>
$(function(){
var highlightWidth=8;
var stage = new Kinetic.Stage({
container: 'container1',
width: 300,
height: 100
});
var layer = new Kinetic.Layer();
stage.add(layer);
var dropzone = new Kinetic.Stage({
container: 'container2',
width: 300,
height: 300
});
var dropLayer = new Kinetic.Layer();
dropzone.add(dropLayer);
// these must go after the creation of stages & layers
addBackground(stage,layer,dropLayer);
layer.draw();
addBackground(dropzone,dropLayer,layer);
dropLayer.draw();
// get images & then trigger start()
var images={};
var URLs = {
house1: 'https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-3.jpg',
house2: 'https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-4.jpg',
house3: 'https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-1.jpg'
};
loadImages(URLs,start);
function start(){
var house1=kImage(images.house1,10,10,50,50,layer);
var house2=kImage(images.house2,75,10,50,50,layer);
var house3=kImage(images.house3,140,10,50,50,layer);
layer.draw();
}
function swapStagesIfSelected(sourceLayer,destinationLayer,startX,startY){
// get all elements on the source layer
var elements=sourceLayer.get("Image");
// don't let dropped elements fall off the stage
var totalWidth=0;
var maxHeight=-999;
var layerWidth=destinationLayer.getStage().getWidth();
var layerHeight=destinationLayer.getStage().getHeight();
for(var i=0;i<elements.length;i++){
if(elements[i].isSelected){
totalWidth+=elements[i].getWidth();
maxHeight=Math.max(elements[i].getHeight(),maxHeight);
}
}
if(startX+totalWidth>layerWidth){
startX=layerWidth-totalWidth-15;
}
if(startY+maxHeight>layerHeight){
startY=layerHeight-maxHeight-15;
}
// move all selected images
// to the clicked x/y of the destination layer
for(var i=0;i<elements.length;i++){
var element=elements[i];
if(element.isSelected){
var img=element.getImage();
kImage(img,startX,startY,element.getWidth(),element.getHeight(),destinationLayer);
startX+=element.getWidth()+10;
element.remove();
}
}
sourceLayer.draw();
destinationLayer.draw();
}
// build the specified KineticJS Image and add it to the specified layer
function kImage(image,x,y,width,height,theLayer){
var image=new Kinetic.Image({
image:image,
x:x,
y:y,
width:width,
height:height,
strokeWidth:0.1,
stroke:"green",
draggable:true
});
image.myLayer=theLayer;
image.isSelected=false;
image.on("click",function(){
highlight(this);
this.myLayer.draw();
});
image.myLayer.add(image);
return(image);
}
// build a background image and add it to the specified stage
function addBackground(theStage,theLayer,otherLayer){
var background = new Kinetic.Rect({
x: 0,
y: 0,
width: theStage.getWidth(),
height: theStage.getHeight(),
fill: "white",
stroke: "green",
strokeWidth: 1
});
background.on("click",function(){
var pos=theStage.getMousePosition();
var mouseX=parseInt(pos.x);
var mouseY=parseInt(pos.y);
swapStagesIfSelected(otherLayer,theLayer,mouseX,mouseY);
});
theLayer.add(background);
}
///////////// Image loader
function loadImages(URLs, callback) {
var loaded = 0;
var needed = 0;
for(var url in URLs) { needed++; console.log(url); }
for(var url in URLs) {
images[url] = new Image();
images[url].onload = function() {
if(++loaded >= needed) {
callback(images);
}
};
images[url].src = URLs[url];
}
}
///////////// Toggle Highlighting
function highlight(element,setStrokeWidth){
if(setStrokeWidth){
element.setStrokeWidth(setStrokeWidth);
}else{
if(element.getStrokeWidth()>5){
element.setStrokeWidth(0.1);
element.isSelected=false;
}else{
element.setStrokeWidth(highlightWidth);
element.isSelected=true;
}
}
}
}); // end $(function(){});
</script>
</head>
<body>
<p>Click on image(s) to toggle selection</p>
<p>Then click in the other canvas to drop</p>
<div id="container1"></div>
<div id="container2"></div>
<button id="clear">Clear Hightlights</button>
<button id="swap">Swap Selected</button>
</body>
</html>

move, delete and retrieve added rectangles positions in a HTML5 canvas

I have this code below to add a rectangle to a canvas, I have some questions regarding this.
Is it possible to move the added rectangle after it has been created?
Is it possible to delete a rectangle that has been added?
Can I retrieve all added rectangles positions (x, y, width and height) after I have added a bunch of rectangles and lets say by click of a button?
<script>
function rect()
{
var canvas = document.getElementById('drawing'),
ctx = canvas.getContext('2d'),
rect = {},
drag = false;
function init() {
canvas.addEventListener('mousedown', mouseDown, false);
canvas.addEventListener('mouseup', mouseUp, false);
canvas.addEventListener('mousemove', mouseMove, false);
}
function mouseDown(e) {
rect.startX = e.pageX - this.offsetLeft;
rect.startY = e.pageY - this.offsetTop;
drag = true;
}
function mouseUp() {
drag = false;
}
function mouseMove(e) {
if (drag) {
rect.w = (e.pageX - this.offsetLeft) - rect.startX;
rect.h = (e.pageY - this.offsetTop) - rect.startY ;
//ctx.clearRect(0,0,canvas.width,canvas.height);
draw();
}
}
function draw() {
ctx.globalAlpha=0.5; // Half opacity
ctx.fillStyle= "#b0c2f7";
//ctx.fillStyle = "rgba(255, 255, 255, 0.05)";
ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);
}
init();
}
</script>
<div id="canvasDiv">
<canvas id="drawing" width="580px" height="788px" style="border:2px solid #000; background: #FFF;"></canvas>
</div>
<script>
var canvas = document.getElementById('drawing');
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(imageObj, 69, 50);
};
imageObj.src = 'http://localhost/test/Images/DSC0273446.jpg';
</script>
<div id="rect">
<p><button onclick="rect();">Rectangle</button></p>
</div>
Really appreciate all help I can get in this matter, thanks!
Is it possible to move the added rectangle after it has been created?
No, once drawn it is just pixels, there is no 'rectangle object' in the canvas. The usual approach to 'moving' a shape in canvas is to clearRect() (or the whole canvas) and then fillRect() in a slightly different position in a requestAnimationFrame controlled loop.
Is it possible to delete a rectangle that has been added?
As long as you've stored the location where you drew it, you can clearRect(). Note that this clears an area of pixels, not an object - the results of previous drawing operations will not automatically reappear.
Can I retrieve all added rectangles positions (x, y, width and height) after I have added a bunch of rectangles and lets say by click of a button?
No. The canvas does not store drawn objects, only pixel image data. If you want to keep track of the objects that have been drawn then you have to do that yourself. If you want to manipulate shapes instead of pixels then there are libraries like fabric.js which add an object manipulation layer on top of canvas, or you can use an svg element instead which will let you create graphics with normal DOM methods.

Mouse Coordinates in HTML5 Canvas

I have tried many different ways of trying to get mouse coordinates in HTML5 canvas in compliment with video and none have seemed too work very well in either Chrome or Safari.
At the moment I am using:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
<script src="modernizr-1.6.min.js"></script>
<script type="text/javascript">
window.addEventListener('load', eventWindowLoaded,false);
var videoElement;
var VideoDiv;
var Object1;
var Mouse = {
x:0
x:y}
function eventWindowLoaded(){
videoElement = document.createElement("video");
videoDiv = document.createElement('div');
document.body.appendChild(videoDiv);
videoDiv.appendChild(videoElement);
videoDiv.setAttribute("style", "display:none;");
var videoType = supportedVideoFormat(videoElement);
if (videoType == ""){
alert("no video support");
return;
}
videoElement.setAttribute("src", "different_movement>" + videoType);
videoElement.addEventListener("canplaythrough", videoLoaded, false);
}
function supportedVideoFormat(video){
var returnExtension= "";
if(video.canPlayType("video/webm") =="probably" || video.canPlayType("video/webm") == "maybe"){
returnExtension = "webm";
} else if (video.canPlayType("video/mp4") == "probably" || video.canPlayType("video/mp4") == "maybe"){
returnExtension = "mp4";
}else if(video.canPlayType("video/ogg") == "probably" || video.canPlayType("video/ogg") == "maybe"){
returnExtension = "ogv";
}
return returnExtension;
}
function videoLoaded(event){
canvasApp();
}
canvasOne.onmousemove = function (event){
Mouse={
x: event.offsetX,
y: event.offsetY}
}
}
function canvasApp(){
function drawScreen(){
context.drawImage(videoElement, 0, 0);
context.fillStyle = '#ffffff';
context.fillText(Mouse.x, 280, 280);
context.fillText(Mouse.y, 280, 300);
}
var theCanvas = document.getElementByID('canvasOne');
var context = theCanvas.getContext('2d');
videoElement.play();
setinterval(drawScreen, 33);
}
</script>
</head>
<body>
<canvas id="canvasOne" width="640" height="480">
Your browser does not support HTML5 Canvas.
</canvas>
</div>
</body>
</html>
The result of this is the 0,0 will be shown on the video from the initial variable set at 0,0 but then instead of changing as the mouse is moved around the screen, it stays 0,0. This leads me to believe that it is the part of the code that is finding the mouse coordinates that is not working.
I have tried various other attempts at finding mouse coordinates including:
Mouse={
x: event.pageX,
y: event.pageX}
,
if (e.pageY) {
posy = e.pageY;
} else if (e.clientY) {
posy = e.clientY + document.body.scrollTop
+ document.documentElement.scrollTop;
}
,
var mouseX;
var mouseY;
var pieceX;
var pieceY;
if (e.pageX || e.pageY) {
mouseX = e.pageX;
mouseX = e.pageY;
} else {
mouseX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
mouseY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
My end product is supposed to be a video that has mouse interactions that will play sounds when certain parts on the video are clicked (thus the part of video). I have tried not using canvas at all for this, and instead positioning a image on top of the canvas which has image mapping on it, but it doesn't seem to work.
Another issue I am going to run into when I figure out mouse coordinates is what I will test collisions with the mouse coordinates to initiate it to play the sounds.
EDIT:
Completely rewrote the code using e.offset, seems to work.
I used <iframe> to set an html page with a canvas element positioned top left of document. Then when I get clientX-Y it's origin is the top left of the canvas document, that's in the iframe, that you can have positioned anywhere on the canvas-containing document. It's easy as pie.
<iframe scrolling="no" height="100%" width="100%" src="canvas.html"></iframe>
also, I got the canvas to scale when it is scaled by style sheet. I added this to my canvas program.
c = canvas element, ctx = canvas context;
ctx.scale(c.width/630,c.height/800); // I originally intended it to be 630x800
(note: I am not sure if this answers your problem, but it is how I find coordinates without having to offset.)