Unable to use the full space of canvas - javascript

I need to use the full space of canvas to draw. But here unable to use the top and left of the canvas to draw. I try make some changes in css, still no luck. Please help.
p.s. By clicking the button the canvas will popup.
<button onClick="openPopup();">click here</button>
<div id="test" class="popup">
<div class="cancel" onclick="closePopup();"></div>
<canvas id="canvas1" width="750" height="720" style="border: 1px solid black"></canvas>
</div>
<style>
.popup{
position:absolute;
top:0px;
left:0px;
margin:0px;
width: 900px;
height: 750px;
font-family:verdana;
font-size:13px;
padding:2px;
background-color:white;
border:2px solid grey;
z-index:100000000000000000;
display:none;
opacity:0.6;
filter:alpha(opacity=60);
margin-left: 300px;
margin-top: 90px;
overflow: auto;
}
.cancel{
display:relative;
cursor:pointer;
margin:0;
float:right;
height:10px;
width:14px;
padding:0 0 5px 0;
background-color:red;
text-align:center;
font-weight:bold;
font-size:11px;
color:white;
border-radius:3px;
z-index:100000000000000000;
}
.cancel:hover{
background:rgb(255,50,50);
}
</style>
<script>
function openPopup() {
document.getElementById('test').style.display = 'block';
}
function closePopup() {
document.getElementById('test').style.display = 'none';
}
var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');
var isPressed = false;
var mx = 4, my = 4;
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;
// waaaay oversimplified:
function getMouse(e) {
var element = can, offsetX = 0, offsetY = 0;
mx = e.pageX;
my = e.pageY;
}
</script>

The drawing point is not synced with mouse pointer.
That is the reason why you can't draw at the left part and the top part of the canvas, because the mouse is already out of the canvas if you try to draw something nearby the left edge.
Notice that how you get the current position of the drawing point:
function getMouse(e) {
var element = can, offsetX = 0, offsetY = 0;
mx = e.pageX;
my = e.pageY;
}
the variable e refers to mouseEvent object. and e.pageX means the distance between the mouse and the left side of the page, NOT YOUR CANVAS. So you should minus the left offset of the canvas from mx and do the same to my, so that the drawing point is right on where you want.
One simple solution:
set the canvas's margin, border and padding to 0;
.popup{
//everything else..
boder: 0;
margin-left: 0px;
margin-top: 0px;
}
Better solution:
minus the left offset to mx and my
function getMouse(e) {
var element = can, offsetX = 0, offsetY = 0;
mx = e.pageX - 305;
my = e.pageY - 95;
//Dynamically getting those padding and margin and border would be better!
}

Related

Why OffsetTop and offsetLeft not working?

I have my canvas and when I click I get X and Y, e.g. x=10 y=10, and when I use scrollbar drop and click in the same position I will get x= not 10 and y=not 10. Why?
<canvas></canvas>
<script>
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
topCanvas = canvas.offsetTop;
leftCanvas = canvas.offsetLeft;
function click(e)
{
console.log("x="+(e.clientX-leftCanvas));
console.log("y="+(e.clientY-topCanvas));
}
</script>
Why scrollbar not helping..
let canvas = document.querySelector('canvas');
let topCanvas = canvas.offsetTop;
let leftCanvas = canvas.offsetLeft;
canvas.addEventListener('click', e => {
console.log('not considering scroll position');
console.log(" x=" + (e.clientX - leftCanvas));
console.log(" y=" + (e.clientY - topCanvas));
console.log('considering scroll position');
console.log(" x=" + e.layerX);
console.log(" y=" + e.layerY);
});
div {
border: 1px solid;
max-height: 300px;
overflow: auto;
}
canvas {
border: 1px solid;
width: 500px;
height: 1000px;
margin-left: 30px;
margin-top: 30px;
}
<div>
<canvas></canvas>
</div>

making ball to fall from top to bottom when the button is clicked

I wrote a program to animate the ball when the button is clicked. It is a part of experiment for a bigger project:
Here is the screen shot:
Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>HTML5 Random Bouncing Ball</title>
<style type="text/css">
<!--
body { background-color:#ededed; font:normal 12px/18px Arial, Helvetica, sans-serif; }
h1 { display:block; width:600px; margin:20px auto; padding-bottom:20px; font:normal 24px/30px Georgia, "Times New Roman", Times, serif; color:#333; text-shadow: 1px 2px 3px #ccc; border-bottom:1px solid #cbcbcb; }
#myCanvas { background:#fff; border:1px solid #cbcbcb; }
#nav { display:block; width:100%; text-align:center; }
#nav li { display:block; font-weight:bold; line-height:21px; text-shadow:1px 1px 1px #fff; width:100px; height:21px; padding:5px; margin:0 10px; background:#e0e0e0; border:1px solid #ccc; -moz-border-radius:4px;-webkit-border-radius:4px; border-radius:4px; float:left; }
#nav li a { color:#000; display:block; text-decoration:none; width:100%; height:100%; }
-->
</style>
<script type="text/javascript">
function myFunction () {
var context;
var dx= 4;
var dy=4;
var y=150;
var x=10;
function draw(){
context= myCanvas.getContext('2d');
context.clearRect(0,0,400,400);
context.beginPath();
context.fillStyle="#000000";
context.arc(x,y,10,0,Math.PI*2,true);
context.closePath();
context.fill();
if( x<0 || x>400)
dx=-dx;
if( y<0 || y>300)
dy=-dy;
x+=dx;
y+=dy;
}
setInterval(draw,10);
}
</script>
</head>
<body>
<div id="container">
<canvas id="myCanvas" width="400" height="300"></canvas>
</div>
<input id="button" type="submit" name="button" value="enter" onclick="myFunction();"/>
</body>
</html>
How can I make the ball to fall from top to bottom when the button is pressed?
There are few steps, you need to do, first, disable the vertical speed (you dont need to delete it, just set it to 0), then in the "draw" function delete the if loops, and create a new, like this:
if (y >= 300) {
y = 290; // Set the ball's Y position to the bottom of the canvas
dy = 0; //And finally this set the falling is zero
}
And if you want it more complicated, create a new variable, "gravity", and in every turn increase the dy variable with the gravity. Then the code above must to look like this:
if (y >= 300) {
y = 290; // Set the ball's Y position to the bottom of the canvas
dy = 0; //And finally this set the falling is zero
gravity = 0;
}
What I did was:
function myFunction () {
var context;
var dx= 4;
var dy=4;
var y=50;
var x=10;
function draw(){
context= myCanvas.getContext('2d');
context.clearRect(0,0,400,400);
context.beginPath();
context.fillStyle="#FFBAA3";
context.arc(x,y,10,0,Math.PI*2,true);
context.closePath();
context.fill();
if( x<0 || x>100)
dx=-dx;
if( y<0 || y>300)
dy=0;
//x+=dx;
y+=dy;
}
setInterval(draw,10);
}
Here is the code, what you need:
function myFunction () {
var context;
var dy=4; //First: dx must be 0;
var dx = 0;
var y=150;
var x=10;
function draw(){
context= myCanvas.getContext('2d');
context.clearRect(0,0,400,400);
context.beginPath();
context.fillStyle="#000000";
context.arc(x,y,10,0,Math.PI*2,true);
context.closePath();
context.fill();
if (y >= 300) { //Second: delete all if loop and add this
y = 290; // |
dy = 0; // <-------------------------------|
}
x+=dx;
y+=dy;
}
setInterval(draw,10);
}`
EDIT:
And a tip: Press F12 in the browser, and click on the Console (or log under some browsers) and you got all the error message's.
If you want, to the ball fall straight down, then dont give him a vertical movement.
EDIT:
If you need that, the ball dont go off the screen, then simply set the x and y position next to the wall.

How to make this tooltip like this with pure javascript

I need to use JS no JQuery plugins to make a simple tooltip like on the image below.
Click on ? image should open this tooltip and click again on the same image to close it.
I think that it's simple for someone with good JS knowledge but I can't do it anyway :(
This is something that I have tried I know it's not too much but I am simply stuck.
How to display it like on the image, how to hide it when it's open and how to add that little triangle in the corner?
myfiddle
<img id="info" src="http://www.craiglotter.co.za/wp-content/uploads/2009/12/craig_question_mark_icon1.png"/>
<div id="ttip">bla bla</div>
document.getElementById('info').addEventListener('click', function(){
// how to check if it's visible so I can close tooltip
document.getElementById('ttip').style.display="block";
});
#info{margin-left:100px;margin-top:50px;}
#ttip
{
width: 280px;
z-index: 15001;
top: 0px;
left: 0px;
display: none;
border-color: #666;
background-color: #fff;
color: #666;
position: relative;
border: 1px solid #666;
padding: 15px 9px 5px 9px;
text-align: left;
word-wrap: break-word;
overflow: hidden;
}
Clean up the css and this will basically do it:
<script>
function doTip(e){
var elem = e.toElement;
if(elem.getAttribute('data-tip-on') === 'false') {
elem.setAttribute('data-tip-on', 'true');
var rect = elem.getBoundingClientRect();
var tipId = Math.random().toString(36).substring(7);
elem.setAttribute('data-tip-id', tipId);
var tip = document.createElement("div");
tip.setAttribute('id', tipId);
tip.innerHTML = elem.getAttribute('data-tip');
tip.style.top = rect.bottom+ 10 + 'px';
tip.style.left = (rect.left-200) + 'px';
tip.setAttribute('class','tip-box');
document.body.appendChild(tip);
} else {
elem.setAttribute('data-tip-on', 'false');
var tip = document.getElementById(elem.getAttribute('data-tip-id'));
tip.parentNode.removeChild(tip);
}
}
function enableTips(){
var elems = document.getElementsByClassName('quick-tip');
for(var i = 0; i < elems.length; i++) {
elems[0].addEventListener("click", doTip, false);
}
}
window.onload = function(){
enableTips();
}
</script>
<style>
.quick-tip {
background: black;
color: #fff;
padding: 5px;
cursor: pointer;
height: 15px;
width: 15px;
text-align: center;
font-weight: 900;
margin-left: 350px;
}
.tip-box {
/* change dimensions to be whatever the background image is */
height: 50px;
width: 200px;
background: grey;
border: 1px solid black;
position: absolute;
}
</style>
<div class="quick-tip" data-tip="THIS IS THE TIP! change elements 'data-tip' to change." data-tip-on="false">?</div>
<script>enableTips(); //might be required for jsfiddle, especially with reloads.</script>
Edit: fixed formatting and a bug. jsfiddle: http://jsfiddle.net/u93a3/
Proof of concept:
The following markup in HTML: Create a div with class tooltip, add image and a div with class info with all text (can be multiple paragraphs if needed, scollbars is shown if necessary):
<div class='tooltip'>
<img src='craig_question_mark_icon1.png' alt='Help'/>
<div class='info'>
Some text to fill the box with.
</div>
</div>
The div.info is set to display:none in CSS.
When the page is loaded a pure javascript is running that draws an image of a triangle on a canvas-element, and then creates a div-element where the triangle is set as a background. Then, for every div.tooltip:
add a click-eventhandler to the image
replace the div.info with a div.info_container
add a clone of the triangle-div to div.info_container
add the original div.info to div.info_container
You can test it with this fiddle. It is tested successfully on FF25, Chrome31, IE10, Opera 12&18.
<!doctype html>
<html>
<head>
<script>
"use strict";
function click(event) {
var elem = this.parentNode.querySelector('div.info_container');
if (elem) elem.style.display = elem.style.display === 'block' ? 'none' : 'block';
}
function toolify() {
var idx,
len,
elem,
info,
text,
elements = document.querySelectorAll('div.tooltip'),
canvas,
imgurl,
pointer,
tipHeight = 20,
tipWidth = 20,
width = 200,
height = 100,
ctx;
// Create a canvas element where the triangle will be drawn
canvas = document.createElement('canvas');
canvas.width = tipHeight;
canvas.height = tipWidth;
ctx = canvas.getContext('2d');
ctx.strokeStyle = '#000'; // Border color
ctx.fillStyle = '#fff'; // background color
ctx.lineWidth = 1;
ctx.translate(-0.5,-0.5); // Move half pixel to make sharp lines
ctx.beginPath();
ctx.moveTo(1,canvas.height); // lower left corner
ctx.lineTo(canvas.width, 1); // upper right corner
ctx.lineTo(canvas.width,canvas.height); // lower right corner
ctx.fill(); // fill the background
ctx.stroke(); // stroke it with border
//fix bottom row
ctx.fillRect(0,canvas.height-0.5,canvas.width-1,canvas.height+2);
// Create a div element where the triangel will be set as background
pointer = document.createElement('div');
pointer.style.width = canvas.width + 'px';
pointer.style.height = canvas.height + 'px';
pointer.innerHTML = ' ' // non breaking space
pointer.style.backgroundImage = 'url(' + canvas.toDataURL() + ')';
pointer.style.position = 'absolute';
pointer.style.top = '2px';
pointer.style.right = '1px';
pointer.style.zIndex = '1'; // place it over the other elements
for (idx=0, len=elements.length; idx < len; ++idx) {
elem = elements[idx];
elem.querySelector('img').addEventListener('click',click);
text = elem.querySelector('div.info');
// Create a new div element, and place the text and pointer in it
info = document.createElement('div');
text.parentNode.replaceChild(info,text);
info.className = 'info_container';
info.appendChild(pointer.cloneNode());
info.appendChild(text);
//info.addEventListener('click',click);
}
}
window.addEventListener('load',toolify);
</script>
<style>
div.tooltip
{
position:relative;
display:inline-block;
width:300px;
text-align:right;
}
div.tooltip > div.info
{
display:none;
}
div.tooltip div.info_container
{
position:absolute;
right:20px;
width:200px;
height:100px;
display:none;
}
div.tooltip div.info
{
text-align:left;
position:absolute;
left:1px;
right:1px;
top:20px;
bottom:1px;
color:#000;
padding:5px;
overflow:auto;
border:1px solid #000;
}
</style>
</head>
<body>
<div class='tooltip'>
<img src='craig_question_mark_icon1.png' alt='Help'/>
<div class='info'>
Some text to fill the box with.
</div>
</div>
<div class='tooltip'>
<img src='craig_question_mark_icon1.png' alt='Help'/>
<div class='info'>
Some text to fill the box with.
Some text to fill the box with.
Some text to fill the box with.
Some text to fill the box with.
</div>
</div>
</body>
</html>

Drawing in canvas become offset

I'm trying to draw into a canvas, but the more I go right, the more offset my drawing become.
Anyone have an idea why?
I have included the relevant code below:
CSS
html,body {
width:100%;
height:100%;
background:rgba(0,0,0,.2);
}
#container {
position:relative;
width:700px;
height:450px;
background:#fff;
overflow:hidden;
}
* {
-webkit-user-select: none;
}
canvas {
position: absolute;
top: 0;
left: 0;
background: #ccc;
width: 500px;
height: 200px;
}
HTML
<div id='adContainer'>
<canvas></canvas>
</div>
Javascript
var ctx;
var can = $('canvas');
$(document).ready(function() {
ctx = can[0].getContext('2d');
ctx.strokeStyle = "rgba(255,0,0,1)";
ctx.lineWidth = 5;
ctx.lineCap = 'round';
can.on("touchstart", function(event) {
event.preventDefault();
var e = event.originalEvent;
if(e.touches.length == 1) {
var posX = e.touches[0].pageX;
var posY = e.touches[0].pageY;
ctx.moveTo(posX, posY);
}
});
can.on("touchmove", function(event) {
event.preventDefault();
var e = event.originalEvent;
if(e.touches.length == 1) {
var posX = e.touches[0].pageX;
var posY = e.touches[0].pageY;
ctx.lineTo(posX, posY);
ctx.stroke();
}
});
});
Demo: http://jsfiddle.net/8Wtf8/
That is because you define the size of the canvas using CSS.
What happens is that when you don't explicitly define the size of the canvas using its width and height attributes the canvas defaults to size 300 x 150.
In your CSS you are then stretching the canvas element (look at it as an image) to 500px etc. - the content of the canvas is still 300 x 150.
You need to set the width and height on the canvas element itself:
<canvas width=500 height=200 id="myCanvas"></canvas>
and remove the definition from the CSS:
canvas {
position: absolute;
top: 0;
left: 0;
background: #ccc;
/*width: 500px;
height: 200px;*/
}
Also notice that background set by CSS will not be part of the canvas content.

Modifying cursor property for select portion of an element

I have this HTML that renders a simple arrow sign pointing towards the right:
<!DOCTYPE html>
<html>
<head>
<style>
div { width: 0px; height: 0px; border-left: 20px solid black; border-top: 20px solid transparent; border-bottom: 20px solid transparent; border-right: 20px solid transparent; position: absolute; left: 35px; top: 53px; cursor: pointer; }
</style>
<body>
<div></div>
</body>
</html>
If you hover of it, the cursor turns to pointer. But because it is actually a square div, the cursor turns pointer even if you are just outside the arrow within the perimeter of the div.
So I wrote this Javascript addition such that the cursor turns pointer only when the mouse is hovering over that arrow. For this purpose, I figured the coordinates of the three vertices of the triangle from Firebug ((35,53),(55,73),(35,93) clockwise from top). Then I check whether the point in question lies inside the triangle formed by these 3 vertices. This I do by checking whether the point and the opposite vertex for each edge lies on the same side of that edge or not (if they do, the product of the values obtained by substituting the coordinates of that point for x and y in that equation will be positive).
<!DOCTYPE html>
<html>
<head>
<style>
div { width: 0px; height: 0px; border-left: 20px solid black; border-top: 20px solid transparent; border-bottom: 20px solid transparent; border-right: 20px solid transparent; position: absolute; left: 35px; top: 53px; }
.hoverclass { cursor: pointer; }
</style>
<script src="jquery.js">
</script>
<script>
$(document).ready(function(){
$("div").click(function(e) { alert(e.pageX + " " + e.pageY); });
function l1(x,y) { return y - x - 18; }
function l2(x,y) { return x+y-128; }
function l3(x,y) { return x-35; }
$("div").hover(function(e) {
var x = e.pageX;
var y = e.pageY;
if (l1(x,y)*l1(35,93) >= 0 && l1(x,y)*l1(35,93) >= 0 && l1(x,y)*l1(35,93) >= 0 ) {
$(this).addClass('hoverclass');
}
else { $(this).removeClass('hoverclass'); }
},
function() {
$(this).removeClass('hoverclass');
});
});
</script>
<body>
<div></div>
</body>
</html>
However, the results are not predictable. Sometimes the cursor turns pointer within the triangle only, sometimes outside as well (just as before), and sometimes not at all. I suspect that this is probably due to the hover function working overtime, that may be temporarily hanging the script. Is there any other way to achieve this?
This could be done using HTML5 canvas. Basic idea is to check for pixel color on mousemove on canvas element. This way, your element can be of any form as you wish. Of course, you should make some optimization of following code:
SEE WORKING DEMO
function findPos(obj) {
var curleft = 0, curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return { x: curleft, y: curtop };
}
return undefined;
}
// set up triangle
var example = document.getElementById('example');
var context = example.getContext('2d');
context.fillStyle = '#000';
context.strokeStyle = '#f00';
context.lineWidth = 1;
context.beginPath();
// Start from the top-left point.
context.moveTo(10, 10); // give the (x,y) coordinates
context.lineTo(60, 60);
context.lineTo(10, 120);
context.lineTo(10, 10);
// Done! Now fill the shape, and draw the stroke.
// Note: your shape will not be visible until you call any of the two methods.
context.fill();
context.stroke();
context.closePath();
$('#example').mousemove(function(e) {
var pos = findPos(this);
var x = e.pageX - pos.x;
var y = e.pageY - pos.y;
var coord = "x=" + x + ", y=" + y;
var c = this.getContext('2d');
var p = c.getImageData(x, y, 1, 1).data;
if(p[3]!='0') $(this).css({cursor:'pointer'});
else $(this).css({cursor:'default'});
});
You'd better use CSS instead. With :before and :after pseudo classes you can do magic. Check out this Pure CSS GUI icons by Nicolas Gallagher.
If you use any CSS pre-processor, these icons can be wrapped up as a mixin, this way required properties can be assigned like this:
#icon > .close(16px, #fff, #E83921);
You can make any shape have cursor pointer with CSS only. The idea is to rotate wrapper container which has overflow: hidden (you can have several of them depending on the shape you need). In case of OP problem this code does a trick:
<div class="arrow"><i></i></div>
.arrow {
margin: 100px;
border_: 1px red solid;
width: 40px;
height: 40px;
overflow: hidden;
-webkit-transform: rotate(45deg);
transform: rotate(45deg);
}
.arrow i {
height: 65px;
width: 65px;
background-color: green;
content: '';
display: block;
cursor: pointer;
margin: -35px 0 0 11px;
-webkit-transform: rotate(45deg);
transform: rotate(45deg);
}
See this demo: http://cssdesk.com/PaB5n
True that this requires CSS transform support so it's not cross browser.

Categories