I am trying to copy the contents of a clipped canvas region. I am using a onmousemove listener to capture a given region, and would like to copy its contents upon the occurence of an onclick event:
var started = false;
editor_canvas.onmousemove = function (e) {
e = e || window.event;
var x = event.pageX;
var y = event.pageY;
if (!started) {
editor_context.beginPath();
editor_context.moveTo(x, y);
started = true;
return;
}
var rect = editor_canvas.getBoundingClientRect();
x = x - rect.left;
y = y - rect.top;
editor_context.lineWidth = 5;
editor_context.strokeStyle = 'red';
editor_context.lineTo(x, y);
editor_context.stroke();
};
editor_canvas.onclick = function(e) {
editor_context.clip();
}
JSFiddle here: http://jsfiddle.net/0nn78uxr/
Related
I am using jsfiddle to store some coordinates. The coordinates gets displayed on jsfiddle but when I copy it on my local files the coordinates don't get displayed.
I would like to display the coordinates of that line on my local files, How can this be done?
This is my HTML file
<canvas id="canvas" width="300" height="300" style="border: 1px solid black;"> </canvas>
<div id="coord"></div>
<div id="coords"></div>
This is my Javascript File
var canvas = document.getElementById('canvas'),
coord = document.getElementById('coord'),
ctx = canvas.getContext('2d'), // get 2D context
imgCat = new Image(),
arr = [];
imgCat.src = ''http://c.wearehugh.com/dih5/openclipart.org_media_files_johnny_automatic_1360.png';
imgCat.onload = function() { // wait for image load
ctx.drawImage(imgCat, 0, 0); // draw imgCat on (0, 0)
};
var mousedown = false;
ctx.strokeStyle = '#0000FF';
ctx.lineWidth = 5;
canvas.onmousedown = function(e) {
arr = [];
var pos = fixPosition(e, canvas);
mousedown = true;
ctx.beginPath();
ctx.moveTo(pos.x, pos.y);
return false;
};
canvas.onmousemove = function(e) {
var pos = fixPosition(e, canvas);
coord.innerHTML = '(' + pos.x + ',' + pos.y + ')';
if (mousedown) {
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
arr.push([pos.x, pos.y])
}
};
canvas.onmouseup = function(e) {
mousedown = false;
$('#coords').html(JSON.stringify(arr, null, 2));
};
function fixPosition(e, gCanvasElement) {
var x;
var y;
if (e.pageX || e.pageY) {
x = e.pageX;
y = e.pageY;
}
else {
x = e.clientX + document.body.scrollLeft +
document.documentElement.scrollLeft;
y = e.clientY + document.body.scrollTop +
document.documentElement.scrollTop;
}
x -= gCanvasElement.offsetLeft;
y -= gCanvasElement.offsetTop;
return {x: x, y:y};
}
Demo Here
Copy this in a html page. The probleme was your link imgCat.src = ''http://c.wearehugh.com/dih5/openclipart.org_media_files_johnny_automatic_1360.png';
You put two ''
<html>
<canvas id="canvas" width="300" height="300" style="border: 1px solid black;"></canvas>
<div id="coord"></div>
<div id="coords"></div>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js</script>
</html>
<script type="text/javascript">
var canvas = document.getElementById('canvas'),
coord = document.getElementById('coord'),
ctx = canvas.getContext('2d'), // get 2D context
imgCat = new Image(),
arr = [];
imgCat.src ='http://www.clipartbest.com/cliparts/bTy/E5x/bTyE5xLjc.png';
imgCat.onload = function() { // wait for image load
ctx.drawImage(imgCat, 0, 0); // draw imgCat on (0, 0)
};
var mousedown = false;
ctx.strokeStyle = '#0000FF';
ctx.lineWidth = 5;
canvas.onmousedown = function(e) {
arr = [];
var pos = fixPosition(e, canvas);
mousedown = true;
ctx.beginPath();
ctx.moveTo(pos.x, pos.y);
return false;
};
canvas.onmousemove = function(e) {
var pos = fixPosition(e, canvas);
coord.innerHTML = '(' + pos.x + ',' + pos.y + ')';
if (mousedown) {
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
arr.push([pos.x, pos.y])
}
};
canvas.onmouseup = function(e) {
mousedown = false;
$('#coords').html(JSON.stringify(arr, null, 2));
};
function fixPosition(e, gCanvasElement) {
var x;
var y;
if (e.pageX || e.pageY) {
x = e.pageX;
y = e.pageY;
}
else {
x = e.clientX + document.body.scrollLeft +
document.documentElement.scrollLeft;
y = e.clientY + document.body.scrollTop +
document.documentElement.scrollTop;
}
x -= gCanvasElement.offsetLeft;
y -= gCanvasElement.offsetTop;
return {x: x, y:y};
}
</script>
some configuration is applying to jsfiddle automatically and you need to apply them by your hands.
first you need to add jQuery to you site. Add this line between <head> </head> tags:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
second you need to check that you script executes for example when page loads. you need to put you code into this:
$(function() {
// You script here
});
or put it just before </body> tag
so in output you jquery code will be like this:
<script>
$(function() {
var canvas = document.getElementById('canvas'),
coord = document.getElementById('coord'),
ctx = canvas.getContext('2d'), // get 2D context
imgCat = new Image(),
arr = [];
imgCat.src = ''http://c.wearehugh.com/dih5/openclipart.org_media_files_johnny_automatic_1360.png';
imgCat.onload = function() { // wait for image load
ctx.drawImage(imgCat, 0, 0); // draw imgCat on (0, 0)
};
var mousedown = false;
ctx.strokeStyle = '#0000FF';
ctx.lineWidth = 5;
canvas.onmousedown = function(e) {
arr = [];
var pos = fixPosition(e, canvas);
mousedown = true;
ctx.beginPath();
ctx.moveTo(pos.x, pos.y);
return false;
};
canvas.onmousemove = function(e) {
var pos = fixPosition(e, canvas);
coord.innerHTML = '(' + pos.x + ',' + pos.y + ')';
if (mousedown) {
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
arr.push([pos.x, pos.y])
}
};
canvas.onmouseup = function(e) {
mousedown = false;
$('#coords').html(JSON.stringify(arr, null, 2));
};
function fixPosition(e, gCanvasElement) {
var x;
var y;
if (e.pageX || e.pageY) {
x = e.pageX;
y = e.pageY;
}
else {
x = e.clientX + document.body.scrollLeft +
document.documentElement.scrollLeft;
y = e.clientY + document.body.scrollTop +
document.documentElement.scrollTop;
}
x -= gCanvasElement.offsetLeft;
y -= gCanvasElement.offsetTop;
return {x: x, y:y};
}
});
</script>
1.Check the doc type of the HTML :should be html for (HTML 5)or no doc type
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
2.Make sure your scripts are getting loaded properly.
Check the path of Jquery script.
--Externally downloaded scripts need to be unblocked
(Righ Click -> Properties -> (General Tab)'Unblock' Option on bottom)
(Right Click -> Properties -> (general Tab) -> Advanced -> Uncheck Encrypt option if checked.)
3.Put your code inside a function.
(Specifically the binding related codes.)
Other functions need to be defined outside document ready.(Already done)
And Call that function inside document ready.
$(document).ready(function () {
DrawImage();
});
function DrawImage()
{
//your code here
var canvas = document.getElementById('canvas'),
coord = document.getElementById('coord'),
ctx = canvas.getContext('2d'), // get 2D context
imgCat = new Image(),
arr = [];
/*********** draw image *************/
imgCat.src = 'http://c.wearehugh.com/dih5/openclipart.org_media_files_johnny_automatic_1360.png';
imgCat.onload = function() { // wait for image load
ctx.drawImage(imgCat, 0, 0); // draw imgCat on (0, 0)
};
/*********** handle mouse events on canvas **************/
var mousedown = false;
ctx.strokeStyle = '#0000FF';
ctx.lineWidth = 5;
canvas.onmousedown = function(e) {
arr = [];
var pos = fixPosition(e, canvas);
mousedown = true;
ctx.beginPath();
ctx.moveTo(pos.x, pos.y);
return false;
};
canvas.onmousemove = function(e) {
var pos = fixPosition(e, canvas);
coord.innerHTML = '(' + pos.x + ',' + pos.y + ')';
if (mousedown) {
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
arr.push([pos.x, pos.y])
}
};
canvas.onmouseup = function(e) {
mousedown = false;
$('#coords').html(JSON.stringify(arr, null, 2));
};
}
//Utils
function fixPosition(e, gCanvasElement) {
//put codes of this function here.
}
just add your script before end of body tag and your problem will solve.
I'm making a drawing pad, and I want the mouse location to update in an array as the mouse is dragged. Here is my code:
function penDown (x, y) {
isPenDown = true;
localPen.x = x;
localPen.y = y;
}
var X = [],
Y = [],
i = -1;
function penMove (x, y) {
if (isPenDown) {
++i;
X[i] = localPen.x;
Y[i] = localPen.y;
console.log("i is " + i + ", x is " + X[i] + ", y is " + Y[i]);
}
};
The console log shows that i is updating continuously when you move the mouse, but the X and Y coordinates of the mouse don't change - they just stay on the initial mouse location when you first press down the mouse.
Here is how I call penDown:
function pointerDownListener (e) {
// Retrieve a reference to the Event object for this mousedown event.
var event = e || window.event;
// Determine where the user clicked the mouse.
var mouseX = event.clientX - canvas.offsetLeft;
var mouseY = event.clientY - canvas.offsetTop;
// Move the drawing pen to the position that was clicked
penDown(mouseX, mouseY);
}
function pointerMoveListener (e) {
var event = e || window.event; // IE uses window.event, not e
var mouseX = event.clientX - canvas.offsetLeft;
var mouseY = event.clientY - canvas.offsetTop;
// Draw a line if the pen is down
penMove(mouseX, mouseY);
}
It might be, because your function penDown is only called once, so the values of x and y assigned to localPen won't change.
I want to keydown trigger the movement of a block and then with another keydown, add another moving block. And if I keydown again, then another moving block appears. As it is now, the keydown stops the movement of the first block. I would like to have all the blocks moving simultaneously. Here's the code. It's also available on jsfiddle http://jsfiddle.net/7eUEE/
Thank you!
var canvas = document.getElementById("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ctx = canvas.getContext("2d");
var w = canvas.width;
var h = canvas.height;
window.addEventListener("keydown", addnew, true);
window.addEventListener("keydown", move, true);
var list = [];
var id = 0;
var color = 'blue';
var x = 0;
var y = 0;
window.onkeydown = function(s){
s.preventDefault();
if(!s){
s = window.event;
}
var keycode;
if(s.which){
keycode = s.which;
}else{
keycode = s.keyCode;
}
}
function box(id, color, x ,y){
box.id = id;
box.color = color;
box.x = x;
box.y = y;
}
function addnew(e){
e.preventDefault();
if(!e){
e = window.event;
}
//space
if(e.keyCode == 32){
list[id] = new box(id, color, x, y);
id++;
y = y + 100;
box.y = y;
box.color = 'red';
console.log(box.y);
}
}
list[0] = box(id, color, x ,y);
function move(e){
e.preventDefault();
if(!e){
e = window.event;
}
//right
if(e.keyCode == 39){
list[id];
setInterval(loopdraw);
}
}
var loopdraw = function draw(){
box.x = box.x + 1;
console.log(box.x);
ctx.beginPath();
ctx.fillStyle = box.color;
ctx.fillRect(box.x, box.y, 50, 50);
ctx.closePath();
}
Your Box objects don't behave like objects, because you use them in 3 ways:
class: list[id] = new box(id, color, x, y);
function: list[0] = box(id, color, x ,y);
object: box.y = y;, box.color = 'red'; etc
The list part is right: keep a collection of (moving) boxes. The loop part isn't, because you don't use the list. You only 'loop' 1 box.
I've updated the fiddle: http://jsfiddle.net/rudiedirkx/7eUEE/1/ and I've renamed the box class to Box, because there might be Box objects named box.
The important parts:
// Create initial box
list[id++] = new Box(id, color, x ,y);
// Create more boxes
list[id++] = new Box(id, 'red', x, y);
// Loop through existing boxes animation
function loopdraw() {
list.forEach(function(box) {
// Draw
I need to do an action onclick of a particular (point) or a rectangle in a canvas.
Example:
$(document).ready(function(){
var canvas = $('#myCanvas').get(0);
if (!canvas.getContext) { return; }
var ctx = canvas.getContext('2d');
ctx.fillRect(150,140,8,8);
ctx.fillRect(200,120,8,8);
ctx.fillRect(200,160,8,8);
});
I need to connect two points with a line and another two points with a curve using javascript .How can i do this?
You need to maintain the regions yourselves. There are no objects on a canvas, only pixels and the browser does not know anything about it.
Demo here
You can do something like this (simplified):
// define the regions - common for draw/redraw and check
var rect1 = [150,140,8,8];
var rect2 = [200,120,8,8];
var rect3 = [200,160,8,8];
var regions = [rect1, rect2, rect3];
Now on your init you can use the same array to render all the rectangles:
$(document).ready(function(){
var canvas = $('#myCanvas').get(0);
if (!canvas.getContext) { return; }
var ctx = canvas.getContext('2d');
//use the array also to render the boxes
for (var i = 0, r; r = regions[i]; i++) {
ctx.fillRect(r[0],r[1],r[2],r[3]);
}
});
On the click event you check the array to see if the mouse coordinate (corrected for canvas) is inside any of the rectangles:
$('#myCanvas').on('click', function(e){
var pos = getMousePos(this, e);
// check if we got a hit
for (var i = 0, r; r = regions[i]; i++) {
if (pos.x >= r[0] && pos.x <= (r[0] + r[2]) &&
pos.y >= r[1] && pos.y <= (r[1] + r[3])) {
alert('Region ' + i + ' was hit');
}
}
});
//get mouse position relative to canvas
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
Also remember to redraw the canvas if the window is re-sized or for other reason clears the canvas (browser dialogs etc.).
To connect the boxes you need to store the first hit position and when you get a second hit draw a line between them.
Demo with lines here
Add to the global vars and also make canvas and context available from global (see fiddle for related modifications in onready):
var x1 = -1, y1;
var canvas = myCanvas;
var ctx = canvas.getContext('2d');
And in the click event:
$('#myCanvas').on('click', function(e){
var pos = getMousePos(this, e);
for (var i = 0, r; r = regions[i]; i++) {
if (pos.x >= r[0] && pos.x <= (r[0] + r[2]) &&
pos.y >= r[1] && pos.y <= (r[1] + r[3])) {
//first hit? then store the coords
if (x1 === -1) {
x1 = pos.x;
y1 = pos.y;
} else {
//draw line from first point to this
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
x1 = -1; //reset (or keep if you want continuous lines).
};
}
}
});
I am using the following function to drag a div by a handle:
function enableDragging(ele) {
var dragging = dragging || false,
x, y, Ox, Oy,
current;
enableDragging.z = enableDragging.z || 1;
var grabber = document.getElementById("wrapId");
grabber.onmousedown = function (ev) {
ev = ev || window.event;
var target = ev.target || ev.srcElement;
current = target.parentNode;
dragging = true;
x = ev.clientX;
y = ev.clientY;
Ox = current.offsetLeft;
Oy = current.offsetTop;
current.style.zIndex = ++enableDragging.z;
document.onmousemove = function (ev) {
ev = ev || window.event;
pauseEvent(ev);
if (dragging == true) {
var Sx = ev.clientX - x + Ox,
Sy = ev.clientY - y + Oy;
current.style.left = Math.max(Sx, Math.min(document.body.offsetWidth - Sx, 0)) + "px";
current.style.top = Math.max(Sy, Math.min(document.body.offsetHeight - Sy, 0)) + "px";
document.body.focus();
document.onselectstart = function () {
return false;
};
ev.ondragstart = function () {
return false;
};
document.body.style.MozUserSelect = "none";
document.body.style.cursor = "default";
return false;
}
}
document.ondragstart = function () {
return false;
}
document.onmouseup = function (ev) {
ev = ev || window.event;
dragging && (dragging = false);
if (ev.preventDefault) {
ev.preventDefault();
} else {
e.cancelBubble = true;
e.returnValue = false;
}
document.body.style.MozUserSelect = "text";
document.body.style.cursor = "default";
//toggleEnableSelectStart(true);
return false;
}
};
}
I am trying to set boundaries to that the div cannot be dragged outside of the bounds of the actual browser window.
The above function accomplished 50% of this, it wont let the user drag the div outside of the top left and left bounds. However it left the user drag it outside bottom and right..
Any ideas how to fix this?
Take the minimum between the value you had calculated with the width/ height boundaries of the window minus the width of/height of the div:
current.style.left = Math.min(Math.max(Sx, Math.min(document.body.offsetWidth - Sx, 0)), document.body.offsetWidth - current.offsetWidth) + "px";
current.style.top = Math.min(Math.max(Sy, Math.min(document.body.offsetHeight - Sy, 0)), document.body.offsetHeight - current.offsetHeight) + "px";
edit:
Something along these lines (mind, this is quickly written, not in the same format as yours!)
http://jsfiddle.net/WKLa7/1/