the drawing not synced with mouse pointer, same goes to touch screen. I have set function getMouse(e) offset for mouse coordinates and function draw(event) for touch coordinates. It is only works for my pc. It doesn't compatible with different touch screen pcs. Where i should make changes and how. Please help.
here is the coding
http://jsfiddle.net/gFXam/
HTML
<button onClick="openPopup();">drawing</button>
<div id="test" class="popup" >
<canvas id="canvas1" width="790" height="1110" style=" border:solid #00F"> </canvas>
<p> </p>
</div>
CSS
<style>
#canvas1 {
left:0; /* adjust as needed */
top:0;
position: inline;
width: 100%;
height: 100%;
}
.popup{
position:absolute;
top:0px;
left:0px;
margin:0px;
width: 764px;
height: 1120px;
font-family:verdana;
font-size:13px;
background-color:rgba(255, 255, 255, 0);
border:2px solid green;
z-index:100000000000000000;
display:none;
opacity:0.6;
filter:alpha(opacity=60);
margin-left: 400px;
margin-top: 100px;
}
.cancel{
display:relative;
cursor:pointer;
margin:0;
float:right;
height:10px;
width:14px;
padding:0 0 5px 0;
background-image:url(/images/icon-cross.png);
text-align:center;
font-weight:bold;
font-size:11px;
color:white;
border-radius:3px;
z-index:100000000000000000;
}
.cancel:hover{
background-color:#09F;
}
</style>
SCRIPT :
<script>
function openPopup() {
var p = document.getElementById('test');
p.style.display = 'block';
canvas.width = parseInt(p.style.width, '10'); //only when you use pixels
canvas.height = parseInt(p.style.height, '10');
}
function closePopup() {
document.getElementById('test').style.display = 'none';
}
function choosecolor(cps) {
ctx.strokeStyle = cps; // red
}
var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');
var isPressed = false;
var mx = 4, my = 4;
//http://stackoverflow.com/questions/2142535/how-to-clear-the-canvas-for-redrawing
function clear_canvas_width ()
{
var s = document.getElementById ("canvas1");
var w = s.width;
s.width = 4;
s.width = w;
ctx.clear();
}
function move(e) {
getMouse(e);
if (isPressed) {
ctx.lineTo(mx, my);
ctx.stroke()
}
}
function up(e) {
getMouse(e);
isPressed = false;
}
function down(e) {
getMouse(e);
ctx.beginPath();
ctx.moveTo(mx, my);
isPressed = true;
}
can.onmousemove = move;
can.onmousedown = down;
can.onmouseup = up;
// for mouse:
function getMouse(e) {
var element = can, offsetX = 0, offsetY = 0;
mx = e.pageX - 400;
my = e.pageY - 108;
}
/*For touch screen*/
window.addEventListener('load',function(){
// get the canvas element and its context
var canvas = document.getElementById('canvas1');
var context = canvas.getContext('2d');
// 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){
// get the touch coordinates
var coors = {
x: event.targetTouches[0].pageX - 400,
y: event.targetTouches[0].pageY - 100
};
// pass the coordinates to the appropriate handler
drawer[event.type](coors);
}
// attach the touchstart, touchmove, touchend event listeners.
canvas.addEventListener('touchstart',draw, false);
canvas.addEventListener('touchmove',draw, false);
canvas.addEventListener('touchend',draw, false);
// prevent elastic scrolling
document.body.addEventListener('touchmove',function(event){
event.preventDefault();
},false); // end body.onTouchMove
},false); // end window.onLoad
</script>
Change your getMouse to this and it should work:
function getMouse(e) {
mx = e.clientX - canvas.offsetLeft;
my = e.clientY - canvas.offsetTop;
}
The mouse positions are relative to the whole page so you need to subtract the offset of the canvas element to get them relative to the canvas.
Related
I am trying to change the FILL COLOR of a SHAPE on Mouseover & Mouseout. Most examples I've seen use the events StageX and StageY coordinates. However, those coordinates are the X & Y positions of the mouse at the time of the event. This forces the object to suddently move when "redrawn".
Other examples ask you to call "GetBounds"...which is not available for Shape objects.
I don't want the object to move simply because I am changing the FillColor
I see nothing resembling the top/left in the EVENT.TARGET
Q: How do I calculate or retrieve the Shapes current X/Y (top/left) coordinates?
THE HTML & JAVASCRIPT:
<style>
.dashboard { height:600px; }
.dashboard header { }
.dashboard aside { vertical-align:top; display:inline-block; }
.dashboard aside.control-bar { border: solid 1px black; border-radius: 3px; padding: 5px; height: 100%; width:10%; margin-right: 5px; }
.dashboard aside.control-bar {}
.dashboard aside.control-bar .btn { width:95%; }
.dashboard section { vertical-align:top; display:inline-block; }
.dashboard section.desktop { height:100%; min-width:80%; border:solid 1px black; border-radius: 3px; }
.dashboard section.desktop canvas { height:98%; width:99%; }
.dashboard footer { margin-top:5px; padding:5px; }
</style>
<div class="row">
<div class="col-md-12">
<main role="main" class="dashboard pb-3">
<header qwik-control="header">
<h3>Dashboard</h3>
</header>
<aside class="control-bar">
<center>
<h6>UI Controls</h6>
<a id="btnCreateNode" class="btn btn-sm btn-dark">Create Node</a>
</center>
</aside>
<section class="desktop">
<canvas id="demoCanvas"></canvas>
</section>
<footer>
<center>
<h5 style="color:#C7C9CD;">Button Controls</h5>
</center>
</footer>
</main>
</div>
</div>
<script src="https://code.createjs.com/1.0.0/createjs.min.js"></script>
<script type="text/javascript">
var stage = null,
loader = null;
// GLOBALS
var _PROPERTIES = { node: { y: 100, x: 200, fillColor: '#F9FAFB', fillOverColor: '#FCFCC2', strokeColor: '#000' } };
function node_create(){
console.log('node_create');
var top = Math.random() * 500;
var left = Math.random() * 500;
var width = _PROPERTIES.node.x;
var height = _PROPERTIES.node.y;
// Create
var node = new createjs.Shape();
node.graphics.beginStroke(_PROPERTIES.node.strokeColor);
node.graphics.beginFill(_PROPERTIES.node.fillColor);
node.graphics.setStrokeStyle(1);
node.snapToPixel = true;
node.graphics.drawRect(left, top, width, height);
node.graphics.endFill();
node.name = name;
node.overColor = _PROPERTIES.node.fillOverColor;
node.outColor = _PROPERTIES.node.fillColor;
// Events
node.on("mouseover", node_mouseover);
node.on("mouseout", node_mouseout);
// Display
stage.addChild(node);
stage.update();
};
function node_mouseover(evt) {
console.log('node_mouseover');
// COORDS is the events coordinates...not the targets Top/Left (e.g. cursor)
// How do I get the X/Y of the target? (getBounds does not exist for Shapes)
var target = evt.target;
var coords = { x: evt.stageX, y: evt.stageY };
target.graphics.clear();
target.graphics.beginStroke(_PROPERTIES.node.strokeColor);
target.graphics.beginFill(target.overColor);
target.graphics.drawRect(coords.x, coords.y, _PROPERTIES.node.x, _PROPERTIES.node.y);
target.graphics.endFill();
stage.update();
};
function node_mouseout(evt) {
console.log('node_mouseout');
// COORDS is the events coordinates...not the targets Top/Left (e.g. cursor)
// How do I get the X/Y of the target? (getBounds does not exist for Shapes)
var target = evt.target;
var coords = { x: evt.stageX, y: evt.stageY };
target.graphics.clear();
target.graphics.beginStroke(_PROPERTIES.node.strokeColor);
target.graphics.beginFill(target.outColor);
target.graphics.drawRect(coords.x, coords.y, _PROPERTIES.node.x, _PROPERTIES.node.y);
target.graphics.endFill();
stage.update();
};
$(document).ready(function () {
// Stage
stage = new createjs.Stage('demoCanvas');
stage.canvas.width = window.innerWidth;
stage.canvas.height = window.innerHeight;
// Stage - Events
stage.enableMouseOver(10);
// Queue
loader = new createjs.LoadQueue();
// DOM - EVENTS
$('#btnCreateNode').on('click', function(e){
node_create();
});
});
</script>
The solution is to put your Shapes into a Container. Shapes don't have the same properties & methods useful in determining location that other objects do: like images or bitmaps etc.
As such...Containers are the "solution" to that.
THE JAVASCRIPT:
var _PROPERTIES = { node: { y: 100, x: 200, fillColor: '#F9FAFB', fillOverColor: '#FCFCC2', strokeColor: '#000' } };
function node_create(){
console.log('node_create');
var top = Math.random() * 500;
var left = Math.random() * 500;
var width = _PROPERTIES.node.x;
var height = _PROPERTIES.node.y;
// Create
var node = new createjs.Shape();
node.graphics.beginStroke(_PROPERTIES.node.strokeColor);
node.graphics.beginFill(_PROPERTIES.node.fillColor);
node.graphics.setStrokeStyle(1);
node.snapToPixel = true;
node.graphics.drawRect(0, 0, width, height); //<-- changed
node.graphics.endFill();
node.name = name;
node.overColor = _PROPERTIES.node.fillOverColor; //<-- added
node.outColor = _PROPERTIES.node.fillColor; //<-- added
// Events
node.on("mouseover", node_mouseover);
node.on("mouseout", node_mouseout);
// Container
var container = new createjs.Container(); //<-- added
container.x = top;
container.y = left;
container.addChild(node);
// Display
stage.addChild(container); //<-- changed
stage.update();
};
function node_mouseover(evt) {
console.log('node_mouseover');
// Because of the container...you no longer need to calculate a TOP or LEFT
var target = evt.target;
target.graphics.clear();
target.graphics.beginStroke(_PROPERTIES.node.strokeColor);
target.graphics.beginFill(target.overColor);
target.graphics.drawRect(0, 0, _PROPERTIES.node.x, _PROPERTIES.node.y); //<-- changed
target.graphics.endFill();
stage.update();
};
function node_mouseout(evt) {
console.log('node_mouseout');
// Because of the container...you no longer need to calculate a TOP or LEFT
var target = evt.target;
target.graphics.clear();
target.graphics.beginStroke(_PROPERTIES.node.strokeColor);
target.graphics.beginFill(target.outColor);
target.graphics.drawRect(0, 0, _PROPERTIES.node.x, _PROPERTIES.node.y); //<-- changed
target.graphics.endFill();
stage.update();
};
i am trying to create an image canvas where user can zoom into the image, the code which i got from here enter link description here, now i tried to add image inside it and i did the following code:
function draw(scale, translatePos) {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
make_base(context);
}
function make_base(context) {
var base_image = new Image();
base_image.src = 'https://www.gstatic.com/webp/gallery3/1.sm.png';
base_image.onload = function() {
context.drawImage(base_image, 0, 0);
}
}
window.onload = function() {
var canvas = document.getElementById("myCanvas");
var translatePos = {
x: canvas.width / 2,
y: canvas.height / 2
};
var scale = 1.0;
var scaleMultiplier = 0.8;
var startDragOffset = {};
var mouseDown = false;
// add button event listeners
document.getElementById("plus").addEventListener("click", function() {
scale /= scaleMultiplier;
draw(scale, translatePos);
}, false);
document.getElementById("minus").addEventListener("click", function() {
scale *= scaleMultiplier;
draw(scale, translatePos);
}, false);
// add event listeners to handle screen drag
canvas.addEventListener("mousedown", function(evt) {
mouseDown = true;
startDragOffset.x = evt.clientX - translatePos.x;
startDragOffset.y = evt.clientY - translatePos.y;
});
canvas.addEventListener("mouseup", function(evt) {
mouseDown = false;
});
canvas.addEventListener("mouseover", function(evt) {
mouseDown = false;
});
canvas.addEventListener("mouseout", function(evt) {
mouseDown = false;
});
canvas.addEventListener("mousemove", function(evt) {
if (mouseDown) {
translatePos.x = evt.clientX - startDragOffset.x;
translatePos.y = evt.clientY - startDragOffset.y;
draw(scale, translatePos);
}
});
draw(scale, translatePos);
};
jQuery(document).ready(function() {
$("#wrapper").mouseover(function(e) {
$('#status').html(e.pageX + ', ' + e.pageY);
});
})
body {
margin: 0px;
padding: 0px;
}
#wrapper {
position: relative;
border: 1px solid #9C9898;
width: 578px;
height: 200px;
}
#buttonWrapper {
position: absolute;
width: 30px;
top: 2px;
right: 2px;
}
input[type="button"] {
padding: 5px;
width: 30px;
margin: 0px 0px 2px 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<body onmousedown="return false;">
<div id="wrapper">
<canvas id="myCanvas" width="578" height="200">
</canvas>
<div id="buttonWrapper">
<input type="button" id="plus" value="+"><input type="button" id="minus" value="-">
</div>
</div>
<h2 id="status">
0, 0
</h2>
</body>
however the image is not getting displayed inside the canvas, can anyone please tell me what could be wrong in here, thanks in advance
Your draw function never actually draws to the canvas. You get the canvas and context in the first 2 lines, but you need to call drawImage with the image to actually add it to the canvas itself.
I suspect you want to be calling make_base inside it like so:
function draw(scale, translatePos) {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
make_base();
}
You also need to have the context in the same scope as you use it. At the moment, the variable context only exists inside the draw function and not the make_base function, so you can't access it from inside make_base.
You can pass it as a variable like so:
function draw(scale, translatePos) {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
make_base(context);
}
function make_base(context) {
var base_image = new Image();
base_image.src = 'a2.jpg';
base_image.onload = function() {
context.drawImage(base_image, 0, 0);
}
}
Every time you want to change anything on an HTML canvas you need to call draw functions to change what's there.
I need to have a cursor to drag and take screenshot of dragged area on HTML webpage. I tried using HTML canvas but it takes screenshot of specific div not the selected region on HTML webpage.
The new html2canvas version 1 has width, height, x and y options.
You can make use of these options to achieve a cropping feature the Firefox's Screenshot's way.
document.onmousedown = startDrag;
document.onmouseup = endDrag;
document.onmousemove = expandDrag;
var dragging = false,
dragStart = {
x: 0,
y: 0
},
dragEnd = {
x: 0,
y: 0
};
function updateDragger() {
dragger.classList.add('visible');
var s = dragger.style;
s.top = Math.min(dragStart.y, dragEnd.y) + 'px';
s.left = Math.min(dragStart.x, dragEnd.x) + 'px';
s.height = Math.abs(dragStart.y - dragEnd.y) + 'px';
s.width = Math.abs(dragStart.x - dragEnd.x) + 'px';
}
function startDrag(evt) {
evt.preventDefault();
dragging = true;
dragStart.x = dragEnd.x = evt.clientX;
dragStart.y = dragEnd.y = evt.clientY;
updateDragger();
}
function expandDrag(evt) {
if (!dragging) return;
dragEnd.x = evt.clientX;
dragEnd.y = evt.clientY;
updateDragger();
}
function endDrag(evt) {
dragging = false;
dragger.classList.remove('visible');
// here is the important part
html2canvas(document.body, {
width: Math.abs(dragStart.x - dragEnd.x),
height: Math.abs(dragStart.y - dragEnd.y),
x: Math.min(dragStart.x, dragEnd.x),
y: Math.min(dragStart.y, dragEnd.y)
})
.then(function(c) {
document.body.appendChild(c);
});
dragStart.x = dragStart.y = dragEnd.x = dragEnd.y = 0;
}
* {
user-select: none;
}
#dragger {
position: fixed;
background: rgba(0, 0, 0, .5);
border: 1px dashed white;
pointer-events: none;
display: none;
}
#dragger.visible {
display: block;
}
canvas {
border: 1px solid;
}
<script src="https://github.com/niklasvh/html2canvas/releases/download/v1.0.0-alpha.1/html2canvas.js"></script>
<div id="wrapper">
<p> Drag to take a screenshot ...</p>
<img crossOrigin src="https://dl.dropboxusercontent.com/s/4e90e48s5vtmfbd/aaa.png" width="120" height="120">
</div>
<div id="dragger" tabindex></div>
I have a problem with my code. It is a simple canvas element drawing circles. There are two things I cannot figure out. The first one is how to draw circles continously (not one at a time) while I keep left mouse button pressed. "Onmousehold" doesn't seem to work here. Secondly is it possible to get rid of the first reference error from the console? It appears only once when coordinates of a click are not yet specified. My code here:
var outer = document.getElementById("outer");
var ctx = outer.getContext("2d");
function getMousePos(e) {
var cursorX = e.clientX;
var cursorY = e.clientY;
x = cursorX;
y = cursorY;
}
function showBox() {
ctx.beginPath();
ctx.arc(x,y,20,0,2*Math.PI);
ctx.stroke();
console.log(x,y);
}
outer.addEventListener("click",getMousePos);
outer.addEventListener("click",showBox);
outer.addEventListener("mousedown",showBox);
#outer {
position:relative;
overflow: hidden;
border: 1px solid green;
}
.popup {
width: 50px;
height: 50px;
border-radius: 25px;
background-color: blue;
position: absolute;
}
<canvas id="outer" width="600" height="600">
</canvas>
And jsfiddle
jsfiddle
see this: http://jsfiddle.net/4ovgzk07/2/
var outer = document.getElementById("outer");
var ctx = outer.getContext("2d");
function getMousePos(e) {
var cursorX = e.clientX;
var cursorY = e.clientY;
x = cursorX;
y = cursorY;
}
function showBox() {
ctx.beginPath();
ctx.arc(x,y,20,0,2*Math.PI);
ctx.stroke();
console.log(x,y);
outer.addEventListener("mousemove",getMousePos);
outer.addEventListener("mousemove",showBox)
outer.addEventListener("mouseup",removelisteners);
}
function removelisteners() {
outer.removeEventListener("mousemove",getMousePos);
outer.removeEventListener("mousemove",showBox)
}
outer.addEventListener("mousedown",getMousePos);
outer.addEventListener("mousedown",showBox);
;
Youu need to attach events for mousemove when mousedown occurs, similarly remove those events on mouseup
I was doing a project on php with java script.I was try to draw a rectangle over a image using javascript.The rectangle can draw any where of the image with any size as compare with image size and also display the co ordinate of drawing rectangle.Please any one help me...I was tried different ways.....
<STYLE>
#rubberBand {
position: absolute;
visibility: hidden;
width: 0px; height: 0px;
border: 2px solid red;
}
</STYLE>
</HEAD>
<BODY>
<img name="myImage" id="myImage" src="a.jpg">
<DIV ID="rubberBand"></DIV>
<SCRIPT>
var IMG;
function startRubber (evt) {
if (document.all) {
var r = document.all.rubberBand;
r.style.width = 0;
r.style.height = 0;
r.style.pixelLeft = event.x;
r.style.pixelTop = event.y;
r.style.visibility = 'visible';
IMG.ondragstart = cancelDragDrop; // otherwise IE will try to drag the image
}
else if (document.getElementById) {
// firefox
evt.preventDefault();
var r = document.getElementById('rubberBand');
r.style.width = 0;
r.style.height = 0;
r.style.left = evt.clientX + 'px';
r.style.top = evt.clientY + 'px';
r.style.visibility = 'visible';
r.onmouseup = stopRubber;
}
IMG.onmousemove = moveRubber;
}
function moveRubber (evt) {
if (document.all) { // IE
var r = document.all.rubberBand;
r.style.width = event.x - r.style.pixelLeft;
r.style.height = event.y - r.style.pixelTop;
}
else if (document.getElementById) { // firefox
var r = document.getElementById('rubberBand');
r.style.width = evt.clientX - parseInt(r.style.left);
r.style.height = evt.clientY - parseInt(r.style.top);
}
return false; // otherwise IE won't fire mouseup :/
}
function stopRubber (evt) {
IMG.onmousemove = null;
}
function cancelDragDrop()
{
window.event.returnValue = false;
}
IMG = document.getElementById('myImage');
IMG.onmousedown = startRubber;
IMG.onmouseup = stopRubber;
</SCRIPT>
You need a wrapper so you can absolutely-position elements inside. The dimensions will vary, depending on your photo and where you want the box.
HTML:
<div class="wrapper">
<img src="...." />
<div class="box"></div>
</div>
CSS:
.wrapper {
position:relative;
}
.box {
position:absolute;
top:10px;
left:10px;
width:50px;
height:50px;
border:2px solid #ffffff;
background-color:transparent
}