I'm creating inside a main div, smaller divs from server side (each div contains data, text and images inside) something like this
I want to allow the user to zoom in or out (incase there are more divs then the screen width for example), in a way that the main div will stay with the same size and only the smaller divs will grow or shrink.
here's an example I've found
that provides the solution I want, but the difference is that:
1. I'm creating the div's during run time , and according to the data , the number of divs may change (the example present default image and div)
2. I want that ALL the divs will zoom in or out together.
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="WebForm3.aspx.vb" Inherits="TEST.WebForm3" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" >
var speed = 4;
function showImage(src) {
var div = document.createElement("div");
with (div.style) {
width = "300px";
height = "300px";
border = "2px solid black";
textAlign = "center";
overflow = "auto";
}
document.body.appendChild(div);
img = document.createElement("img");
img.src = src;
img.width = 300;
img.height = 300;
div.appendChild(img);
}
function keydown(key) {
var k = 0;
if (key == 187) k = speed;
if (key == 189) k = -speed;
if (key != 0) {
img.width = img.width + k;
img.height = img.height + k;
img.style.margin = ((300 - img.height) / 2).toString() + "px";
}
}
</script>
</head>
<body onkeydown="keydown(event.keyCode)" onload="showImage('http://bjstlh.com/data/wallpapers/67/WDF_1122851.jpg')">
<form id="form1" runat="server">
<h1>press (+) to zoom in <br /> press (-) to zoom out</h1>
</form>
</body>
</html>
I'm not too familiar with Javascript - any help would be appreciated
Related
I have a simple html that has multiple div elements.
<body onload="start()">
<div id="image1"></div>
<div id="image2"></div>
</body>
onload event of the body triggers a javascript function called start() that creates two objects from a class called img. The class creates a canvas in the div that it points to (the first parameter) with a width and height stated in the second and third parameters.
function start(){
let img1 = new img("image1",640,480);
let img2 = new img("image2",320,240);
}
The following class creates the canvas and an array which it fills with random numbers between 0-255. It also adds a mousemove event to the object.
class img{
constructor(p_divid, p_w, p_h){
this.divid = p_divid; //DIV id
this.w = p_w; //width of the div
this.h = p_h; //height of the div
this.pixels = []; //pixel values
for (let index = 0; index < this.w*this.h; index++) {
this.pixels[index] = Math.floor(Math.random()*255); //a random value up to 255
}
this.div = document.getElementById(this.divid); //div element
this.div.innerHTML = "<canvas id='canvas-"+this.divid+"' width='"+this.w+"' height='"+this.h+"' style='background-color:red;'></canvas>"; //this creates a canvas
this.canvas = document.getElementById("canvas-"+this.divid); //canvas element
this.canvas.addEventListener("mousemove", this.mmove); //mouse move event
}
the mousemove event gets the coordinates of the mouse relative to the element and calculates the position of the element that it wants to reach in the object's pixels. I want to learn the best practice to reach the objects pixels array.
mmove(e){
var rect = e.target.getBoundingClientRect();
var x = e.clientX - rect.left;
var y = e.clientY - rect.top;
var position_in_array = (y * 640) + x;
//******************************************************************************
//THIS IS WHERE I WOULD LIKE TO GET THE VALUE OF THE PIXELS ARRAY AND
//WRITE IT ON THE CONSOLE. Something like:
//let x = object.pixels[position_in_array];
//******************************************************************************
}
the whole html file that you see above is :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
</head>
<body onload="start()">
<div id="image1"></div>
<div id="image2"></div>
</body>
<script>
function start(){
let img1 = new img("image1",640,480);
let img2 = new img("image2",320,240);
}
class img{
constructor(p_divid, p_w, p_h){
this.divid = p_divid; //DIV id
this.w = p_w; //width of the div
this.h = p_h; //height of the div
this.pixels = []; //pixel values
for (let index = 0; index < this.w*this.h; index++) {
this.pixels[index] = Math.floor(Math.random()*255); //a random value up to 255
}
console.log(this.pixels);
this.div = document.getElementById(this.divid); //div element
this.div.innerHTML = "<canvas id='canvas-"+this.divid+"' width='"+this.w+"' height='"+this.h+"' style='background-color:red;'></canvas>"; //this creates a canvas
this.canvas = document.getElementById("canvas-"+this.divid); //canvas element
this.canvas.addEventListener("mousemove", this.mmove); //mouse move event
}
mmove(e){
var rect = e.target.getBoundingClientRect();
var x = e.clientX - rect.left;
var y = e.clientY - rect.top;
var position_in_array = (y * 640) + x;
//******************************************************************************
//THIS IS WHERE I WOULD LIKE TO GET THE VALUE OF THE PIXELS ARRAY AND
//WRITE IT ON THE CONSOLE. Something like:
//let x = object.pixels[position_in_array];
//******************************************************************************
}
}
</script>
</html>
You can used bind method to pass extra arguments like
this.mmove.bind(null,this.pixels);
mmove(pixels, e){
Here is an example code on how you can pass extra argument with bind
document.querySelector("#btn").addEventListener('click', a.bind(null,12));
function a(v,e){
alert(e.target.textContent);
alert(v);
}
<button id="btn">Click</button>
Thanks to 'charlietfl' for pointing me to the right direction.
changing my addeventlistener line to :
this.canvas.addEventListener("mousemove", this.mmove.bind(this));
and the mmove function to
mmove(e){
var rect = e.target.getBoundingClientRect();
var x = e.clientX - rect.left;
var y = e.clientY - rect.top;
var position_in_array = (y * 640) + x;
let value = this.pixels[position_in_array];
console.log(value);
}
solved my problem.
After abt 2hrs or so, I managed to get the images moving, but i met with some issues:
1) Images move beyond the "bound" - image overlap is ok, but beyond the side of the browser
2) Moving the scroll bar to the right (0 -> 20) makes the image move closer - OK
but moving the scroll bar to the left (20 -> 0) does not return the images back to where they were
I seek you guys assistance to help debug and clean the code.
Thank You in advance :) and apologies for my weak sense of coding >.<
Images Used:
lion tail
lion head
Below is the "Draft" HTML Code:
<!DOCTYPE html>
<html>
<head>
<title>Moving Image</title>
<script src="./movingPicture.js" type="text/javascript"></script>
</head>
<body>
<form>
<img id="IMG_LEFT" src="./lion tail.gif" />
<img id="IMG_RIGHT" src="./lion head.gif" />
<p>Move the Bar to Move the Images Closer</p>
<input type="range" min="0" max="100" value="0" steps="2" oninput="moveRight(value);"/>
</form>
</body>
</html>
Below is the Javascript Code:
var imgObjLeft = null;
var imgObjRight = null;
function init()
{
imgObjLeft = document.getElementById('IMG_LEFT');
imgObjLeft.style.position= 'relative';
imgObjLeft.style.left = '0px';
imgObjRight = document.getElementById('IMG_RIGHT');
imgObjRight.style.position= 'relative';
imgObjRight.style.left = '100px';
}
function moveRight(value)
{
valueH = value/2;
imgObjLeft.style.left = parseInt(imgObjLeft.style.left) + valueH + 'px';
imgObjRight.style.left = parseInt(imgObjRight.style.left) - valueH + 'px';
}
window.onload =init;
Try the following JS. You dont seem to give a range for the movement of these images. I have added a limit which is the max value of your range control. you can increase the value by increasing the max value of your slider
var imgObjLeft = null;
var imgObjRight = null;
function init() {
imgObjLeft = document.getElementById('IMG_LEFT');
imgObjLeft.style.position = 'relative';
imgObjLeft.style.left = '0px';
imgObjRight = document.getElementById('IMG_RIGHT');
imgObjRight.style.position = 'relative';
imgObjRight.style.left = '100px';
}
function moveRight(value) {
valueH = value;
imgObjLeft.style.left = valueH + 'px';
imgObjRight.style.left = (100 - valueH) + 'px';
}
window.onload = init;
How to make the text in a PDF selectable?
Have tried here. The PDF is written fine, but no text selection
https://github.com/mozilla/pdf.js
https://github.com/mozilla/pdf.js/blob/master/web/text_layer_builder.css
https://github.com/mozilla/pdf.js/blob/master/web/text_layer_builder.js
'use strict';
PDFJS.getDocument('file.pdf').then(function(pdf){
var page_num = 1;
pdf.getPage(page_num).then(function(page){
var scale = 1.5;
var viewport = page.getViewport(scale);
var canvas = document.getElementById('the-canvas');
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
var canvasOffset = $(canvas).offset();
var $textLayerDiv = $('#text-layer').css({
height : viewport.height+'px',
width : viewport.width+'px',
top : canvasOffset.top,
left : canvasOffset.left
});
page.render({
canvasContext : context,
viewport : viewport
});
page.getTextContent().then(function(textContent){
var textLayer = new TextLayerBuilder({
textLayerDiv : $textLayerDiv.get(0),
pageIndex : page_num - 1,
viewport : viewport
});
textLayer.setTextContent(textContent);
textLayer.render();
});
});
});
<body>
<div>
<canvas id="the-canvas" style="border:1px solid black;"></canvas>
<div id="text-layer" class="textLayer"></div>
</div>
</body>
On pdf.js version 2.8.61, the checked answer does no more work, as renderTextLayer() is integrated to pdf.js, no more outside source is required, neither jQuery.
The following code will make PDF text selectable. It loads the following PDF document as example, please replace it with your own:
https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/web/compressed.tracemonkey-pldi-09.pdf
It uses mainly two html elements:
<canvas id="the-canvas"></canvas>
<div class="textLayer"></div>
canvas for the non selectable document for display, .textLayer div for selectable text. Text on .textLayer div is all transparent, so invisible, it provides only the selection effect.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no">
<script src="//mozilla.github.io/pdf.js/build/pdf.js" crossorigin="anonymous"></script>
<link href="//mozilla.github.io/pdf.js/web/viewer.css" rel="stylesheet" type="text/css" />
<style type="text/css">
#the-canvas {
border: 1px solid black;
direction: ltr;
}
</style>
</head>
<body>
<h1>PDF.js Previous/Next example</h1>
<div>
<button id="prev">Previous</button>
<button id="next">Next</button>
<span>Page: <span id="page_num"></span> / <span id="page_count"></span></span>
</div>
<canvas id="the-canvas"></canvas>
<div class="textLayer"></div>
<script>
// If absolute URL from the remote server is provided, configure the CORS
// header on that server.
var url = '//raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/web/compressed.tracemonkey-pldi-09.pdf';
// Loaded via <script> tag, create shortcut to access PDF.js exports.
var pdfjsLib = window['pdfjs-dist/build/pdf'];
// The workerSrc property shall be specified.
pdfjsLib.GlobalWorkerOptions.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js';
var pdfDoc = null,
pageNum = 1,
pageRendering = false,
pageNumPending = null,
//scale = 0.8,
scale = 1,
canvas = document.getElementById('the-canvas'),
ctx = canvas.getContext('2d');
/**
* Get page info from document, resize canvas accordingly, and render page.
* #param num Page number.
*/
function renderPage(num) {
pageRendering = true;
// Using promise to fetch the page
pdfDoc.getPage(num).then(function(page) {
var viewport = page.getViewport({scale: scale});
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
var renderContext = {
canvasContext: ctx,
viewport: viewport
};
var renderTask = page.render(renderContext);
// Wait for rendering to finish
renderTask.promise.then(function() {
pageRendering = false;
if (pageNumPending !== null) {
// New page rendering is pending
renderPage(pageNumPending);
pageNumPending = null;
}
}).then(function() {
// Returns a promise, on resolving it will return text contents of the page
return page.getTextContent();
}).then(function(textContent) {
// Assign CSS to the textLayer element
var textLayer = document.querySelector(".textLayer");
textLayer.style.left = canvas.offsetLeft + 'px';
textLayer.style.top = canvas.offsetTop + 'px';
textLayer.style.height = canvas.offsetHeight + 'px';
textLayer.style.width = canvas.offsetWidth + 'px';
// Pass the data to the method for rendering of text over the pdf canvas.
pdfjsLib.renderTextLayer({
textContent: textContent,
container: textLayer,
viewport: viewport,
textDivs: []
});
});
});
// Update page counters
document.getElementById('page_num').textContent = num;
}
/**
* If another page rendering in progress, waits until the rendering is
* finised. Otherwise, executes rendering immediately.
*/
function queueRenderPage(num) {
if (pageRendering) {
pageNumPending = num;
} else {
renderPage(num);
}
}
/**
* Displays previous page.
*/
function onPrevPage() {
if (pageNum <= 1) {
return;
}
pageNum--;
queueRenderPage(pageNum);
}
document.getElementById('prev').addEventListener('click', onPrevPage);
/**
* Displays next page.
*/
function onNextPage() {
if (pageNum >= pdfDoc.numPages) {
return;
}
pageNum++;
queueRenderPage(pageNum);
}
document.getElementById('next').addEventListener('click', onNextPage);
/**
* Asynchronously downloads PDF.
*/
pdfjsLib.getDocument(url).promise.then(function(pdfDoc_) {
pdfDoc = pdfDoc_;
document.getElementById('page_count').textContent = pdfDoc.numPages;
// Initial/first page rendering
renderPage(pageNum);
});
</script>
</body>
</html>
Your javascript code is perfect.
You just need to include the UI utilities that Text Layer Builder depends on:
https://github.com/mozilla/pdf.js/blob/master/web/ui_utils.js
Or in HTML:
<script src="https://raw.githubusercontent.com/mozilla/pdf.js/master/web/ui_utils.js"></script>
If you run your code (without ui_utils) and check the debug console,
you will see ReferenceError: CustomStyle is not defined.
A quick search in PDFjs's repo will show you it is defined in ui_utils.js.
Here is my minimal but complete code for your reference.
I am using PDFjs's demo pdf here.
Note that in production you should not link to raw.github.
<!DOCTYPE html><meta charset="utf-8">
<link rel="stylesheet" href="https://raw.githubusercontent.com/mozilla/pdf.js/master/web/text_layer_builder.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://raw.githubusercontent.com/mozilla/pdf.js/master/web/ui_utils.js"></script>
<script src="https://raw.githubusercontent.com/mozilla/pdf.js/master/web/text_layer_builder.js"></script>
<script src="https://mozilla.github.io/pdf.js/build/pdf.js"></script>
<body>
<div>
<canvas id="the-canvas" style="border:1px solid black;"></canvas>
<div id="text-layer" class="textLayer"></div>
</div>
<script>
'use strict';
PDFJS.getDocument('file.pdf').then(function(pdf){
var page_num = 1;
pdf.getPage(page_num).then(function(page){
var scale = 1.5;
var viewport = page.getViewport(scale);
var canvas = $('#the-canvas')[0];
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
var canvasOffset = $(canvas).offset();
var $textLayerDiv = $('#text-layer').css({
height : viewport.height+'px',
width : viewport.width+'px',
top : canvasOffset.top,
left : canvasOffset.left
});
page.render({
canvasContext : context,
viewport : viewport
});
page.getTextContent().then(function(textContent){
console.log( textContent );
var textLayer = new TextLayerBuilder({
textLayerDiv : $textLayerDiv.get(0),
pageIndex : page_num - 1,
viewport : viewport
});
textLayer.setTextContent(textContent);
textLayer.render();
});
});
});
</script>
After hours of struggling with this I found this article to be very helpful about selecting text and using pdf.js without node.
Custom PDF Rendering in JavaScript with Mozilla’s PDF.Js
Hello you have created canvas in your HTML content.
Canvas will not support text selection so you need to change the canvas to another way.
I have a simple game where image moves randomly and score increases when user clicks on it.
The first image displays before game is started, which when clicked calls the play() function in javascript, which hides that image and displays the image that is to be used for the game.
That is where my code is stuck, it does not call the function play(). I am new to javascript and html. Any help would be great!
Here is my code
<html>
<head>
<title>Image click Game!</title>
<script>
global var score = 0;
global var left=400;
global var top = 100;
function play() {
var game = document.getElementById('game');
var firstDiv = document.getElementById('firstDiv');
var height = window.innerHeight;
var width = window.innerWidth;
firstDiv.style = 'display : none';
game.style='display : block';
setInterval("move()", 1000);
}
function move() {
var randomNumberX = Math.floor(Math.random()*11)-5;
var randomNumberY = Math.floor(Math.random()*11)-5;
left = left + randomNumberX;
top = top+randomNumberY;
var im = document.getElementById('image');
im.style.left = left;
im.style.top = top;
}
</script>
</head>
<body>
<div id ="firstDiv" style="display : block">
<img src="pics/playgame.gif" width="108" height="106" onClick = "play()"/></a>
</div>
<div id="game" style="display : none">
<p>"Score: " + score</p>
<img id="image" src="pics/gameImage.gif" onClick = "score++" style="position:absolute; left: 400; top: 100;"/></a>
</div>
</body>
</html>
There are a handful of things wrong with your code:
1) Your <img> tags are ended with a stray, unneeded </a> tag.
2) In your <img> tag, you should change to onClick = "play();"
3) I don't believe javascript supports the global keyword in that way.
4) To change CSS style, try this:
firstDiv.style.display = 'none';
game.style.display = 'block';
5) You cannot display javascript variables in this fashion: <p>"Score: " + score</p>...not to mention there is no declared variable 'score' to begin with!
Keep working at it, you only get better with practice.
Tyr this
<script>
var score = 0;
var left=400;
var top = 100;
function play() {
var game = document.getElementById('game');
var firstDiv = document.getElementById('firstDiv');
var height = window.innerHeight;
var width = window.innerWidth;
firstDiv.style.display='none';
game.style.display='block';
setInterval("move()", 1000);
}
function move() {
var randomNumberX=Math.floor(Math.random()*11)-5;
var randomNumberY=Math.floor(Math.random()*11)-5;
left= left+randomNumberX;
top = top+randomNumberY;
var im= document.getElementById('image');
im.style.left=left;
im.style.top=top;
}
well right now im trying to learn how to use the canvas tag on html, and im having trouble handling mouse events when i apply css to the document.
the issue starts when i move the div containing the canvas and center it on the page, the first poing of the canvas wouldnt be 0 because its centered and for some reason 0,0 would be the beginning of the screen and not the beginning of the canvas, which i found weird because im adding the event listener to the canvas directly.
here is the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test</title>
<style type="text/css">
body {
font: 100%/1.4 Verdana, Arial, Helvetica, sans-serif;
background: #42413C;
margin: 0;
padding: 0;
color: #000;
}
#divId {
width: 800px;
height: 600px;
text-align:center;
margin: 20px auto;
background-color:#0099FF;
}
</style>
<script>
window.onload = function () {
var canvas = document.getElementById('canvasId');
var c = canvas.getContext('2d');
alert("lol");
canvas.addEventListener('mousedown', hmd, false);
function hmd(e) {
alert ("x: " + e.clientX + " y: " + e.clientY);
}
}
</script>
</head>
<body>
<div id="divId">
<canvas height="300" width="800" id="canvasId" />
</div>
</body>
</html>
so i read somewhere that the issue was caused by the div, but when i tried to give css directly to the canvas tag it didnt work, so basically what i need to do, is to get that canvas centered or placed anywhere on the screen, but having its first pixel as 0,0.
adding a solution would be hard because its centering automatically, so i would need to know the user resolution to be able to calculate the offset so what im looking for is a way to do it simply with css or something.
To get the coordinates relatively to the canvas, do this:
function hmd(e) {
var rx = e.pageX, ry = e.pageY;
rx -= canvas.offsetLeft;
ry -= canvas.offsetTop;
alert ("x: " + rx + " y: " + ry);
}
This assumes your canvas variable definition is global.
Edit: another method:
function hmd(e) {
var rx, ry;
if(e.offsetX) {
rx = e.offsetX;
ry = e.offsetY;
}
else if(e.layerX) {
rx = e.layerX;
ry = e.layerY;
}
}
Here's what I've been using for my latest experimentation. It works with damn near everything: Borders, paddings, position:fixed elements offsetting the HTML element, etc. It also works on all touch devices and even if the browser is zoomed.
http://jsfiddle.net/simonsarris/te8GQ/5/
var stylePaddingLeft = parseInt(document.defaultView.getComputedStyle(can, undefined)['paddingLeft'], 10) || 0;
var stylePaddingTop = parseInt(document.defaultView.getComputedStyle(can, undefined)['paddingTop'], 10) || 0;
var styleBorderLeft = parseInt(document.defaultView.getComputedStyle(can, undefined)['borderLeftWidth'], 10) || 0;
var styleBorderTop = parseInt(document.defaultView.getComputedStyle(can, undefined)['borderTopWidth'], 10) || 0;
var html = document.body.parentNode;
var htmlTop = html.offsetTop;
var htmlLeft = html.offsetLeft;
function getMouse(e) {
var element = can,
offsetX = 0,
offsetY = 0,
mx, my;
// Compute the total offset
if (element.offsetParent !== undefined) {
do {
offsetX += element.offsetLeft;
offsetY += element.offsetTop;
} while ((element = element.offsetParent));
}
// Add padding and border style widths to offset
// Also add the <html> offsets in case there's a position:fixed bar
offsetX += stylePaddingLeft + styleBorderLeft + htmlLeft;
offsetY += stylePaddingTop + styleBorderTop + htmlTop;
mx = e.pageX - offsetX;
my = e.pageY - offsetY;
// We return a simple javascript object (a hash) with x and y defined
return {
x: mx,
y: my
};
}