Draw multiple rectangle on canvas - javascript

I am trying to add multiple rectangle on canvas on mouse move. But when I am drawing rectangle on image, back image on canvas is also cleared. I don't want to remove it. I want multiple rectangle on canvas without clearing canvas image. Please check below JavaScript code.
var canvas = document.getElementById('canvasarea'),
context = canvas.getContext('2d');
base_image = new Image();
base_image.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg'; //Load Image ;
base_image.onload = function(){
context.drawImage(base_image,0,0);
}
var strokeWidth = 4;
drawCount = 1;
canvas.addEventListener("mousemove", function (e) {
drawRectangleOnCanvas.handleMouseMove(e);
}, false);
canvas.addEventListener("mousedown", function (e) {
drawRectangleOnCanvas.handleMouseDown(e);
}, false);
canvas.addEventListener("mouseup", function (e) {
drawRectangleOnCanvas.handleMouseUp(e);
}, false);
canvas.addEventListener("mouseout", function (e) {
drawRectangleOnCanvas.handleMouseOut(e);
}, false);
function reOffset(){
var BB=canvas.getBoundingClientRect();
recOffsetX=BB.left;
recOffsetY=BB.top;
}
var recOffsetX,recOffsetY;
reOffset();
window.onscroll=function(e){ reOffset(); }
window.onresize=function(e){ reOffset(); }
var isRecDown=false;
var startX,startY;
var rects=[];
var newRect;
var drawRectangleOnCanvas={
handleMouseDown:function(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
startX=parseInt(e.clientX-recOffsetX);
startY=parseInt(e.clientY-recOffsetY);
// Put your mousedown stuff here
isRecDown=true;
},
handleMouseUp:function(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
mouseX=parseInt(e.clientX-recOffsetX);
mouseY=parseInt(e.clientY-recOffsetY);
// Put your mouseup stuff here
isRecDown=false;
//if(!willOverlap(newRect)){
rects.push(newRect);
//}
drawRectangleOnCanvas.drawAll();
},
drawAll:function(){
context.clearRect(0, 0, canvas.width, canvas.height);
context.lineWidth=strokeWidth;
//context.strokeStyle=$('div.dropdown-menu').find('.selected').attr('data-color');
for(var i=0;i<rects.length;i++){
var r=rects[i];
context.strokeStyle = r.color;
context.globalAlpha=1;
context.strokeRect(r.left,r.top,r.right-r.left,r.bottom-r.top);
context.beginPath();
context.arc(r.left, r.top, 15, 0, Math.PI*2, true);
context.closePath();
context.fillStyle = r.color;
context.fill();
var text = drawCount;
context.fillStyle = "#fff";
var font = "bold " + 2 +"px serif";
context.font = font;
var width = context.measureText(text).width;
var height = context.measureText("w").width; // this is a GUESS of height
context.fillText(text, r.left - (width/2) ,r.top + (height/2));
}
},
handleMouseOut:function(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
mouseX=parseInt(e.clientX-recOffsetX);
mouseY=parseInt(e.clientY-recOffsetY);
// Put your mouseOut stuff here
isRecDown=false;
},
handleMouseMove:function(e){
if(!isRecDown){return;}
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
mouseX=parseInt(e.clientX-recOffsetX);
mouseY=parseInt(e.clientY-recOffsetY);
newRect={
left:Math.min(startX,mouseX),
right:Math.max(startX,mouseX),
top:Math.min(startY,mouseY),
bottom:Math.max(startY,mouseY),
color:"#000000"
}
drawRectangleOnCanvas.drawAll();
context.strokeStyle = "#000000";
context.lineWidth = strokeWidth;
context.globalAlpha=1;
context.strokeRect(startX,startY,mouseX-startX,mouseY-startY);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvasarea"></canvas>

After clearing the canvas you need to draw the image as well in your drawAll() method. context.drawImage(base_image, 0, 0);
var canvas = document.getElementById('canvasarea'),
context = canvas.getContext('2d');
var base_image = new Image();
base_image.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg'; //Load Image ;
base_image.onload = function() {
context.drawImage(base_image, 0, 0);
}
function drawImage() {
}
var strokeWidth = 4;
drawCount = 1;
canvas.addEventListener("mousemove", function(e) {
drawRectangleOnCanvas.handleMouseMove(e);
}, false);
canvas.addEventListener("mousedown", function(e) {
drawRectangleOnCanvas.handleMouseDown(e);
}, false);
canvas.addEventListener("mouseup", function(e) {
drawRectangleOnCanvas.handleMouseUp(e);
}, false);
canvas.addEventListener("mouseout", function(e) {
drawRectangleOnCanvas.handleMouseOut(e);
}, false);
function reOffset() {
var BB = canvas.getBoundingClientRect();
recOffsetX = BB.left;
recOffsetY = BB.top;
}
var recOffsetX, recOffsetY;
reOffset();
window.onscroll = function(e) {
reOffset();
}
window.onresize = function(e) {
reOffset();
}
var isRecDown = false;
var startX, startY;
var rects = [];
var newRect;
var drawRectangleOnCanvas = {
handleMouseDown: function(e) {
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
startX = parseInt(e.clientX - recOffsetX);
startY = parseInt(e.clientY - recOffsetY);
// Put your mousedown stuff here
isRecDown = true;
},
handleMouseUp: function(e) {
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
mouseX = parseInt(e.clientX - recOffsetX);
mouseY = parseInt(e.clientY - recOffsetY);
// Put your mouseup stuff here
isRecDown = false;
//if(!willOverlap(newRect)){
rects.push(newRect);
//}
drawRectangleOnCanvas.drawAll();
},
drawAll: function() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(base_image, 0, 0);
context.lineWidth = strokeWidth;
for (var i = 0; i < rects.length; i++) {
var r = rects[i];
context.strokeStyle = r.color;
context.globalAlpha = 1;
context.strokeRect(r.left, r.top, r.right - r.left, r.bottom - r.top);
context.beginPath();
context.arc(r.left, r.top, 15, 0, Math.PI * 2, true);
context.closePath();
context.fillStyle = r.color;
context.fill();
var text = drawCount;
context.fillStyle = "#fff";
var font = "bold " + 2 + "px serif";
context.font = font;
var width = context.measureText(text).width;
var height = context.measureText("w").width; // this is a GUESS of height
context.fillText(text, r.left - (width / 2), r.top + (height / 2));
}
},
handleMouseOut: function(e) {
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
mouseX = parseInt(e.clientX - recOffsetX);
mouseY = parseInt(e.clientY - recOffsetY);
// Put your mouseOut stuff here
isRecDown = false;
},
handleMouseMove: function(e) {
if (!isRecDown) {
return;
}
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
mouseX = parseInt(e.clientX - recOffsetX);
mouseY = parseInt(e.clientY - recOffsetY);
newRect = {
left: Math.min(startX, mouseX),
right: Math.max(startX, mouseX),
top: Math.min(startY, mouseY),
bottom: Math.max(startY, mouseY),
color: "#000000"
}
drawRectangleOnCanvas.drawAll();
context.strokeStyle = "#000000";
context.lineWidth = strokeWidth;
context.globalAlpha = 1;
context.strokeRect(startX, startY, mouseX - startX, mouseY - startY);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvasarea"></canvas>

Related

How to draw rectangle in canvas which is already in pdf.js

am using pdf.js here am rendering my pdf in canvas,
My code is:
<div id="viewerContainer" tabindex="0">
<div id="viewer" class="pdfViewer"></div>
</div>
The above canvas is generating through viewer.js
Now I am trying to draw rectangle on my pdf, but its not showing my rectangle,
My script is in below:
<script type="text/javascript">
var canvas, context, startX, endX, startY, endY;
var mouseIsDown = 0;
function init() {
canvas = document.getElementById("page1");
context = canvas.getContext("2d");
canvas.addEventListener("mousedown", mouseDown, false);
canvas.addEventListener("mousemove", mouseXY, false);
canvas.addEventListener("mouseup", mouseUp, false);
}
function mouseUp() {
if (mouseIsDown !== 0) {
mouseIsDown = 0;
drawSquare(); //update on mouse-up
}
}
function mouseDown() {
mouseIsDown = 1;
startX = endX = event.clientX - canvas.offsetLeft; //remember to subtract
startY = endY = event.clientY - canvas.offsetTop; //canvas offset
drawSquare(); //update
}
function mouseXY(eve) {
if (mouseIsDown !== 0) {
if (!eve) {
var eve = event;
}
endX = event.pageX - canvas.offsetLeft;
endY = event.pageY - canvas.offsetTop;
drawSquare();
}
}
function drawSquare() {
// creating a square
var width = Math.abs(startX - endX);
var height = Math.abs(startY - endY);
context.clearRect(0, 0, context.width, context.height);
//or use fillRect if you use a bg color
context.beginPath();
context.rect(startX, startY, width, height);
context.fillStyle = "yellow";
context.fill();
context.lineWidth = 7;
context.strokeStyle = 'black';
context.stroke();
}
</script>
viwer.js code:
var canvasWrapper = document.createElement('div');
canvasWrapper.style.width = div.style.width;
canvasWrapper.style.height = div.style.height;
canvasWrapper.classList.add('canvasWrapper');
if (this.annotationLayer && this.annotationLayer.div) {
div.insertBefore(canvasWrapper, this.annotationLayer.div);
} else {
div.appendChild(canvasWrapper);
}
var textLayer = null;
if (this.textLayerFactory) {
var textLayerDiv = document.createElement('div');
textLayerDiv.className = 'textLayer';
textLayerDiv.style.width = canvasWrapper.style.width;
textLayerDiv.style.height = canvasWrapper.style.height;
if (this.annotationLayer && this.annotationLayer.div) {
div.insertBefore(textLayerDiv, this.annotationLayer.div);
} else {
div.appendChild(textLayerDiv);
}
textLayer = this.textLayerFactory.createTextLayerBuilder(textLayerDiv, this.id - 1, this.viewport, this.enhanceTextSelection);
}
var viewport = this.viewport;
var canvas = document.createElement('canvas');
canvas.id = this.renderingId;
canvas.setAttribute('hidden', 'hidden');
var isCanvasHidden = true;
var showCanvas = function showCanvas() {
if (isCanvasHidden) {
canvas.removeAttribute('hidden');
isCanvasHidden = false;
}
};
canvasWrapper.appendChild(canvas);
Is there any mistake in my code? I have searched many source but I could not able to find the correct one. Kindly help me in this issue.

Blur part of the image with Javascript/Jquery

I'm trying to blur a part of the photo. My code is as follows:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var rect = {};
var drag = false;
var imageObj = null;
function init() {
imageObj = new Image();
imageObj.onload = function () { ctx.drawImage(imageObj, 0, 0); };
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
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) {
ctx.clearRect(0, 0, 500, 500);
ctx.drawImage(imageObj, 0, 0);
rect.w = (e.pageX - this.offsetLeft) - rect.startX;
rect.h = (e.pageY - this.offsetTop) - rect.startY;
ctx.strokeStyle = 'blue';
ctx.strokeRect(rect.startX, rect.startY, rect.w, rect.h);
ctx.filter = 'blur(5px)';
}
}
//
init();
<canvas id="canvas" width="500" height="500"></canvas>
I draw a rectangle but I want to apply the blur filter only on that rectangle not to the whole image as it is now. Any idea how to do that?
Here is the fiddle
It is possible by using HTML5 Canvas
I have made a fiddle to blur the part 350 from image.
Fiddle Link: https://jsfiddle.net/k6aaqdx6/3/
Edit:
updated according to your fiddle: https://jsfiddle.net/tbjLk6eu/2
Code that I added:
imgData=ctx.getImageData(rect.startX, rect.startY, rect.w, rect.h);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.filter = 'none';
ctx.drawImage(imageObj, 0, 0);
ctx.putImageData(imgData,rw, rh);
ctx.strokeRect(rect.startX, rect.startY, rect.w, rect.h);
working jsfiddle: https://jsfiddle.net/zoh5o9p5/
If you use a base64 image and do some changes it will work as you expected
made some changes in mouseMove function.
function mouseMove(e) {
if (drag) {
ctx.filter = 'blur(5px)';
ctx.drawImage(imageObj, 0, 0);
rect.w = (e.pageX - this.offsetLeft) - rect.startX;
rect.h = (e.pageY - this.offsetTop) - rect.startY;
ctx.strokeStyle = 'blue';
if(rect.w>0 && rect.h>0)
{
imgDrow=ctx.getImageData(rect.startX, rect.startY, rect.w, rect.h);
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.filter = 'none';
ctx.drawImage(imageObj, 0, 0);
w=rect.w<0?rect.startX+rect.w:rect.startX;
h=rect.h<0?rect.startY+rect.h:rect.startY;
if(imgDrow)
{
ctx.putImageData(imgDrow,w, h);
}
ctx.strokeRect(rect.startX, rect.startY, rect.w, rect.h);
}
working jsfiddle: https://jsfiddle.net/zoh5o9p5/
we can use fabric.js library. Here you can draw a rectangle and move it and resize it. The original fiddle was having some console error and scaling was not working. I have resolved them all in the bellow jsfiddle.
Here we first copy the original image and create a copy canvas and make the full image blur. Then on move or scaling of the rectangle just showing actual crop to show the proper blur section.
function blurSelection(left=0, top=0, img=null) {
if (img) {
img.cropX = left;
img.cropY = top;
fabricCanvas.renderAll();
} else {
const image = fabric.Image.fromURL(blurredCanvas.toDataURL(), function (img) {
img.cropX = left;
img.cropY = top;
img.width = 200; // Default
img.height = 100; // Default
img.objectCaching = false;
fabricCanvas.add(img);
img.bringToFront();
img.on('moving', function (options) {
const newLeft = options.target.left;
const newTop = options.target.top;
blurSelection(newLeft, newTop, img=options.target);
});
img.on('scaling', function (options) {
const newLeft = options.target.left;
const newTop = options.target.top;
const newWidth = options.target.width * options.target.scaleX;
const newHeight = options.target.height * options.target.scaleY;
//console.log("scaleX",options.target.scaleX,'scaleY',options.target.scaleX,"newWidth",newWidth,"newHeight",newHeight)
options.target.scaleX=1;
options.target.scaleY=1;
options.target.width=newWidth;
options.target.height=newHeight;
})
});
}
}
function copyCanvas() {
const objects = fabricCanvas.getObjects();
const copiedCanvas = fabricCanvas.toCanvasElement();
const blurredImage = new fabric.Image(copiedCanvas);
const filter = new fabric.Image.filters.Blur({
blur: 0.8
});
blurredImage.filters.push(filter);
blurredImage.applyFilters();
blurredCanvas = new fabric.Canvas(copiedCanvas);
window.blurredCanvas = blurredCanvas;
blurredCanvas.add(blurredImage);
blurredCanvas.renderAll();
// Just for the inspection of the blurred image
document.getElementById('asd').src = copiedCanvas.toDataURL();
}
https://jsfiddle.net/debchy/ajbpefk4/7/

How can I make canvas drawing work on mobile

My canvas drawing interface works perfectly on desktop but fails to work on iPhone.
When I try to draw, it just makes a dot where my thumb goes. When I drag my thumb, there is no line and the page continues to scroll...
Code:
var clearButton = document.getElementById('doodle-bin');
var canvascontainer = document.getElementById('doodle-canvas-container');
var canvas = document.getElementById('doodle-canvas');
var context = canvas.getContext('2d');
var radius = (document.getElementById('doodle-canvas-container').clientWidth + document.getElementById('doodle-canvas-container').clientHeight) / 150;
var dragging = false;
function getMousePosition(e) {
var mouseX = e.offsetX * canvas.width / canvas.clientWidth | 0;
var mouseY = e.offsetY * canvas.height / canvas.clientHeight | 0;
return {x: mouseX, y: mouseY};
}
context.mozImageSmoothingEnabled = false;
context.imageSmoothingEnabled = false;
canvas.width = 1280;
canvas.height = 720;
canvas.style.width = '100%';
canvas.style.height = '100%';
/* CLEAR CANVAS */
function clearCanvas() {
context.clearRect(0, 0, canvas.width, canvas.height);
}
clearButton.addEventListener('click', clearCanvas);
var putPoint = function (e) {
if (dragging) {
context.lineTo(getMousePosition(e).x, getMousePosition(e).y);
context.lineWidth = radius * 2;
context.stroke();
context.beginPath();
context.arc(getMousePosition(e).x, getMousePosition(e).y, radius, 0, Math.PI * 2);
context.fill();
context.beginPath();
context.moveTo(getMousePosition(e).x, getMousePosition(e).y);
}
};
var engage = function (e) {
dragging = true;
putPoint(e);
};
var disengage = function () {
dragging = false;
context.beginPath();
};
canvas.addEventListener('mousedown', engage);
canvas.addEventListener('mousemove', putPoint);
canvas.addEventListener('mouseup', disengage);
document.addEventListener('mouseup', disengage);
canvas.addEventListener('contextmenu', disengage);
canvas.addEventListener('touchstart', engage, false);
canvas.addEventListener('touchmove', putPoint, false);
canvas.addEventListener('touchend', disengage, false);
Any help would be greatly appreciated! Thank you
In your putPoint function cancel the default events and propagation.
var putPoint = function (e) {
e.preventDefault();
e.stopPropagation();
if (dragging) {
....
Then look at Using Touch Events with the HTML5 Canvas to handle how to convert your touch coordinates to mouse coordinates.
canvas.addEventListener("touchmove", function (e) {
var touch = e.touches[0];
var mouseEvent = new MouseEvent("mousemove", {
clientX: touch.clientX,
clientY: touch.clientY
});
canvas.dispatchEvent(mouseEvent);
}, false);

Replacing color with photo in html drawing tool

In this drawing tool for html I want to replace the color (#ddd) with a photo.
Instead of the current version I want to replace the grey rectangle with a photo. Any idea on how to do that? And it won't let me reposition the rectangle, any idea why?
(function() {
function createCanvas(parent, width, height) {
var canvas = {};
canvas.node = document.createElement('canvas');
canvas.context = canvas.node.getContext('2d');
canvas.node.width = width || 100;
canvas.node.height = height || 100;
parent.appendChild(canvas.node);
return canvas;
}
function init(container, width, height, fillColor) {
var canvas = createCanvas(container, width, height);
var ctx = canvas.context;
// define a custom fillCircle method
ctx.fillCircle = function(x, y, radius, fillColor) {
this.fillStyle = fillColor;
this.beginPath();
this.moveTo(x, y);
this.arc(x, y, radius, 0, Math.PI * 2, false);
this.fill();
};
ctx.clearTo = function(fillColor) {
ctx.fillStyle = fillColor;
ctx.fillRect(0, 0, width, height);
};
ctx.clearTo(fillColor || "#ddd");
// bind mouse events
canvas.node.onmousemove = function(e) {
if (!canvas.isDrawing) {
return;
}
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
var radius = 25; // or whatever
var fillColor = '#ff0000';
ctx.globalCompositeOperation = 'destination-out';
ctx.fillCircle(x, y, radius, fillColor);
};
canvas.node.onmousedown = function(e) {
canvas.isDrawing = true;
};
canvas.node.onmouseup = function(e) {
canvas.isDrawing = false;
};
}
var container = document.getElementById('canvas');
init(container, 400, 400, '#ddd');
})();
You can achieve this by layering a solid canvas on top of another canvas. Erasing parts of the top canvas should reveal the canvas below.
The following reuses 99% of the code from two separate posts.
Loading the image onto the canvas.
Erasing the top canvas (layer).
// Borrowed from here: https://stackoverflow.com/a/4776378
var canvasWrapper = document.getElementsByClassName('layer-wrapper')[0];
var imageLayer = canvasWrapper.querySelector('.layer-image');
var drawLayer = canvasWrapper.querySelector('.layer-draw');
var img = new Image;
img.onload = function() {
imageLayer.width = drawLayer.width = img.width;
imageLayer.height = drawLayer.height = img.height;
var imageCtx = imageLayer.getContext('2d');
imageCtx.drawImage(img, 0, 0);
var drawCtx = drawLayer.getContext('2d');
drawCtx.fillStyle = '#7F7F7F';
drawCtx.fillRect(0, 0, img.width, img.height);
};
img.src = 'https://pbs.twimg.com/profile_images/462372073982025728/jTHaxsxd.jpeg';
// Borrowed from here: https://stackoverflow.com/a/25916334
var RADIUS = 32;
var canvas = canvasWrapper.querySelector('.layer-wrapper .layer-draw');
var ctx = canvas.getContext('2d');
var lastX;
var lastY;
var strokeColor = 'red';
var strokeWidth = 5;
var mouseX;
var mouseY;
var canvasOffset = $(canvas).offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var isMouseDown = false;
function handleMouseDown(e) {
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
// Put your mousedown stuff here
lastX = mouseX;
lastY = mouseY;
isMouseDown = true;
}
function handleMouseUp(e) {
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
// Put your mouseup stuff here
isMouseDown = false;
}
function handleMouseOut(e) {
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
// Put your mouseOut stuff here
isMouseDown = false;
}
function handleMouseMove(e) {
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
// Put your mousemove stuff here
if (isMouseDown) {
ctx.beginPath();
if (mode == "pen") {
ctx.globalCompositeOperation = "source-over";
ctx.moveTo(lastX, lastY);
ctx.lineTo(mouseX, mouseY);
ctx.stroke();
} else {
ctx.globalCompositeOperation = "destination-out";
ctx.arc(lastX, lastY, RADIUS, 0, Math.PI * 2, false);
ctx.fill();
}
lastX = mouseX;
lastY = mouseY;
}
}
$(canvas).mousedown(function(e) {
handleMouseDown(e);
}).mousemove(function(e) {
handleMouseMove(e);
}).mouseup(function(e) {
handleMouseUp(e);
}).mouseout(function(e) {
handleMouseOut(e);
});
var mode = 'eraser';
//$('#pen') .click(function() { mode = 'pen'; });
//$('#eraser').click(function() { mode = 'eraser'; });
.layer-wrapper {
position: relative;
width: 400px;
height: 300px;
}
.layer-wrapper canvas.layer {
position: absolute;
top: 0;
left: 0;
}
.layer-image {
z-index: 1;
}
.layer-draw {
z-index: 100;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="layer-wrapper">
<canvas class="layer layer-image"></canvas>
<canvas class="layer layer-draw"></canvas>
</div>

How can I move an obj inside a canvas using touch event?

Hello everybody I've just trying to understands how this does it work
I have a basic canvas base just in javascript and I would like to move it using touch event
I'm not sure about this but Can I use the drag event ?
Do I need to use a loop function ?
How can I trigger that blue cube ?
I know there are lot of javascript engine in fact i'm using phaser but I would like to undertand this
Thank you
var canvas, cx, width, height;
var cube = {
x: 80,
y: 100,
update: function () {
},
draw: function (ctx) {
ctx.save();
ctx.fillStyle = "blue";
ctx.fillRect(100, 410, 50, 50);
ctx.restore();
}
};
function onpress(e) {
e.preventDefault();
var whichArt = e.target;
var touch = e.touches[0];
var moveOffsetX = whichArt.offsetLeft - touch.pageX;
var moveOffsetY = whichArt.offsetTop - touch.pageY;
whichArt.addEventListener('touchmove', function () {
var positionX = touch.pageX + moveOffsetX;
var positionY = touch.pageY + moveOffsetY;
cube.x = positionX;
cube.y = positionY;
console.log(cube.x);
}, false);
}
function main() {
canvas = document.createElement("canvas");
width = window.innerWidth;
height = window.innerHeight;
if (width >= 500) {
width = 320;
height = 480;
canvas.style.border = "1px solid #000";
}
document.addEventListener("touchstart", onpress);
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
run();
}
function run() {
var loop = function () {
update();
render();
window.requestAnimationFrame(loop, canvas);
}
window.requestAnimationFrame(loop, canvas);
}
function update() {
}
function render() {
cube.draw(ctx);
}
main();
http://jsfiddle.net/marcogomesr/sxbo3r83/
The canvas is only a passive drawing surface : You have to handle the drag by yourself.
Below a short example :
draggables object have to implement isPointInside, and to be added to the list of draggables object.
I used a dragData object that stores the list of draggables object, the currently dragged object, maybe you'll want to store the start/current point of the drag, and handle a drag-offset so the user holds the object right on the point where he/she started dragging.
http://jsfiddle.net/3ksvn4y0/3/
var canvas, cx, width, height;
var canvasRect;
var cube1, cube2;
var dragData = {
draggables: [],
start: { x: 0, y: 0
},
current: { x: 0, y: 0
},
target: null
};
function Cube(x,y,w,h, color) {
this.x=x; this.y=y; this.w=w; this.h = h;
this.color = color;
}
Cube.prototype = {
update: function () {
},
draw: function (ctx) {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.w, this.h);
},
isPointInside: function (x, y) {
return (x >= this.x) && (x < this.x + this.w) && (y > this.y) && (y < this.y + this.h);
}
};
var pointerCoords = {
x: 0,
y: 0,
update: function (e) {
var coords = e.touches ? e.touches[0] : e;
this.x = coords.pageX - canvasRect.left;
this.y = coords.pageY - canvasRect.top;
}
};
function onStart(e) {
e.preventDefault();
pointerCoords.update(e);
// look if we start the touch within a draggable object
var target = null;
for (var i = 0; i < dragData.draggables.length; i++) {
var draggable = dragData.draggables[i];
if (draggable.isPointInside(pointerCoords.x, pointerCoords.y)) {
target = draggable;
break;
}
}
dragData.target = target;
}
function onMove(e) {
pointerCoords.update(e);
var target = dragData.target;
if (!target) return;
target.x = pointerCoords.x;
target.y = pointerCoords.y;
}
function onStop(e) {
pointerCoords.update(e);
e.preventDefault();
if (!dragData.target) return;
onMove(e);
dragData.target = null;
}
function main() {
canvas = document.createElement("canvas");
width = window.innerWidth;
height = window.innerHeight;
if (width >= 500) {
width = 320;
height = 480;
canvas.style.border = "1px solid #000";
}
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
canvasRect = canvas.getBoundingClientRect();
canvas.addEventListener("touchstart", onStart);
canvas.addEventListener('touchmove', onMove);
canvas.addEventListener("touchstop", onStop);
canvas.addEventListener("mousedown", onStart);
canvas.addEventListener('mousemove', onMove);
canvas.addEventListener("mouseup", onStop);
cube1 = new Cube(100, 80, 30, 30, 'blue');
cube2 = new Cube(150, 160, 20, 20, 'red');
dragData.draggables.push(cube1, cube2);
run();
}
function run() {
var loop = function () {
requestAnimationFrame(loop);
update();
render();
}
loop();
}
function update() {
}
function render() {
ctx.clearRect(0, 0, width, height);
cube1.draw(ctx);
cube2.draw(ctx);
}
main();

Categories

Resources