dragging and dropping images into a Web page and automatically resizing them with HTML File API - html

I want to create Web pages that allow users to drag and drop images into boxes in various parts of the page, so that they can then print the pages with their images.
I want the image to automatically resize when it's dropped in the box. I combined some of the code at http://html5demos.com/file-api with some of the code at http://html5demos.com/file-api-simple to get something like I want.
In the current version of the code (below), the image width does not resize the first time you drop the image into the box, but it does the second time.
Any suggestions how I can get the image width to resize automatically the first time you drop the image into the box?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8 />
<meta name="viewport" content="width=620" />
<title>HTML5 Test</title>
</head>
<body>
<header>
<h1>HTML5 Test 1</h1>
</header>
<style>
#holder { border: 10px dashed #ccc; width: 300px; height: 300px; margin: 20px auto;}
#holder.hover { border: 10px dashed #333; }
</style>
<article>
<div id="holder"></div>
<p id="status">File API & FileReader API not supported</p>
<p>Drag an image from your desktop on to the drop zone above to see the browser read the contents of the file - without uploading the file to any servers.</p>
</article>
<script>
var holder = document.getElementById('holder'),
state = document.getElementById('status');
if (typeof window.FileReader === 'undefined') {
state.className = 'fail';
} else {
state.className = 'success';
state.innerHTML = 'File API & FileReader available';
}
holder.ondragover = function () { this.className = 'hover'; return false; };
holder.ondragend = function () { this.className = ''; return false; };
holder.ondrop = function (e) {
this.className = '';
e.stopPropagation();
e.preventDefault();
var file = e.dataTransfer.files[0],
reader = new FileReader();
reader.onload = function (event) {
var img = new Image();
img.src = event.target.result;
// note: no onload required since we've got the dataurl...I think! :)
if (img.width > 300) { // holder width
img.width = 300;
}
holder.innerHTML = '';
holder.appendChild(img);
};
reader.readAsDataURL(file);
return false;
};
</script>
</body>
</html>

I found a simple answer that I think works really well for my needs, based on a bit of CSS in http://demos.hacks.mozilla.org/openweb/DnD/dropbox.css used for http://demos.hacks.mozilla.org/openweb/DnD/.
In the code I included in my question above, I added this to the CSS code:
#holder > * {
display: block;
margin: auto;
max-width: 300px;
max-height: 300px;
}
and I deleted this:
if (img.width > 300) { // holder width
img.width = 300;
}

Related

get size of displayed web page without browser application bars with css

I am creating a simple web page that displays text from a text input, and I want to make the text input to take up the whole displayed web page (without the browser bar), the 100vh technique includes the browser bar and I do not want to guess the top bar size
Here is my code:
function focus() { // to easily focus an element
document.getElementById("title").focus();
}
document.addEventListener('click', function (event) { // make sure the user's focus is stuck to the text input
if (event.target !== document.getElementById("title")) {
document.getElementById("title").focus();
}
}, false);
window.onload = function () {document.getElementById("title").focus();};
function apply() { // applies title
setTimeout(function () {
var str = document.getElementById("title").value;
if (!str.replace(/\s/g, '').length) {
document.title = "title-text";
} else {
document.title = str;
}
},1);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>title-text</title>
</head>
<body>
<input type="text" id="title" onkeypress="apply()" autocomplete="off">
</body>
</html>
(the JS binds the focus to the text box)
Use the following css classes to achieve this.
body{
margin:0;
overflow:hidden;
}
#title{
height: 100vh;
width:100vw;
}

the page render in disorder after switching from landscape to portrait in ios 9

i set a div's width 100% in css, it initial ok in portrait mode.i rotate my iphone to landscape mode , and then switch to portrait mode.unfortunately the page render in disorder,it appear that the div is zoom out. The problem page is showed as follow:
The page contains two parts, the image area's width and height are set via JavaScript, blow the image is the div i mentioned before, it seems zoom out after roating from landscape to portrait mode.I have put the meta tag viewport in head ,which is set as
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
I think i have find the answer to this question.Because my code is so complex, i simplify it as follows:
<div class="wrapMv clearfix" id="playArea">
<div class="mv" id="playerContainer">
<div class="mvPlayer" id="mvPlayer">
<!--<video id="player" src="" autoplay controls></video>-->
<div id="posterImgDiv" class="poster-img-div">
<img id="postImg" class="poster-img" src="">
</div>
</div>
</div>
</div>
<div id="main" class="main clearfix">
<div style="height: 10px;"></div>
<div id="sayContent" class="sayContent">
<h3>大家都在说</h3>
<ul id="chatArea">
</ul>
</div>
</div>
this is the html code.
var player = {
init : function() {
var ua = navigator.userAgent.toLowerCase();
this.isIos = (/(iphone|ipad|ipod)/i).test(ua);
if (this.isIos) {
this.iosVersion = this._getIOSVersion(ua);
}
this.canUseNativeFullApi = (/(qqbrowser|ucbrowser|micromessenger)/i).test(ua);
this.isModenBrowser = this.isIos | this.canUseNativeFullApi;
this._initPlayerDom();
},
_getIOSVersion : function (ua) {
if (/cpu (?:iphone )?os (\d+_\d+)/.test(ua)){
return parseFloat(RegExp.$1.replace("_", "."));
} else {
return 2;
}
},
_orientationChangeHandler : function() {
var self = this;
setTimeout(function() {
var isLandscape = false;
if ( window.orientation == 180 || window.orientation== 0 ) {
$('body').removeClass('landscape');
window.scrollTo(0, 0);console.log('竖屏');////
} else if( window.orientation == 90 || window.orientation == -90 ) {//横屏
$('body').addClass('landscape');
isLandscape = true;
}
self.resizePlayer(isLandscape,true);//
}, 300);
},
_addOrientationListener : function() {
var self = this;
if (this.isModenBrowser) {console.log('use orientationchange');
window.addEventListener('orientationchange', function(){
self._orientationChangeHandler();
});
} else {console.log('use resize event');
$(window).resize(function() {
self._orientationChangeHandler();
});
}
},
_initPlayerDom : function() {
this._addOrientationListener();
var $player;
$('#mvPlayer').append( '<video x-webkit-airplay="allow" webkit-playsinline id="player" ></video>');
$player = $('#player');
this.$player = $player;
},
resizePlayer : function(isLandscape,noNeedResizeChatContent) {
var self = this;
var currentInnerHeight = window.innerHeight;
var playerWidth = window.innerWidth;
var playerHeight = playerWidth * 9 / 16;
if (playerHeight > currentInnerHeight) {
playerWidth = currentInnerHeight * 16 / 9;
playerHeight = currentInnerHeight;
}
setTimeout(function() {
$('#playerContainer').height(playerHeight).width(playerWidth);
$('#player').height(playerHeight).width(playerWidth);
},10);
}
};
This is the js code.The key point of this problem is hide in the function of resizePlayer. Let see the code var playerWidth = window.innerWidth; and $('#player').height(playerHeight).width(playerWidth);,when you rotate your iphone ,the video's height and width will be recumputed.After I debug my page via weinre, i found that when switch from landscape to portrait,the value of window.innderWidth got from ios9 war wrong and always bigger than factual value.
The style set in css :
.mv{
margin: 0 auto;
width: 100%;
}
.mvPlayer{
margin: 0 auto;
width: 100%;
}
.main{
overflow-y: scroll;
width: 100%;
height: auto;
display: inline-block;
}
Finally ,i resolved the problem.I add a style in css:
.mvPlayer video {
width: 100%;
}
And not set the width of the player in javascript:
$('#playerContainer').height(playerHeight);
$('#player').height(playerHeight);

Canvas element not showing up

I'm very new to programming and am trying to make a project for class using html, canvas, and a css file. The concept is that there should be a title screen that appears in the canvas element that once you click will disappear and reveal a room where there are elements that you can hover your mouse over and get information.
I have the html, canvas, and css up to how I want it but whenever I try to put something in the canvas element it doesn't show up. Like, for the title screen I want to draw a colored box and put some text in it and then have it click away to reveal an image underneath. I used a drawCanvas but it will only show up if I put a gameLoop at the end. But when I try to add text, it disappears. Again, I'm really new to this and I'm sorry for my wall of text but any advice or suggestions would be really helpful. Here's my html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title Page</title>
<link rel="stylesheet" type="text/css" href="css.css"/>
<script src="js/modernizr.js"></script>
<script>
window.addEventListener("load",eventWindowLoaded, false);
function eventWindowLoaded() {
canvasApp();
}
function canvasSupport() {
return Modernizr.canvas;
}
function canvasApp() {
if (!canvasSupport()) {
return;
}
var theCanvas = document.getElementById("canvasOne");
var context = theCanvas.getContext("2d");
var width=1000;
var height=450;
function drawCanvas(){
context.fillStyle="teal";
context.fillRect(0,0,width,height);
setColor();
drawLines();
}
function gameLoop(){
requestAnimationFrame(gameLoop);
drawCanvas();
}
gameLoop();
}
</script>
</head>
<body>
<audio loop="loop" autoplay="autoplay" controls="controls">
<source src="themesong.mp3" type="audio/mpeg">
Your browser does not support the audio content.
</audio>
<!-- Canvas -->
<div id="canvas-container">
<canvas id="canvasOne" width="1000" height="450">
Your browser does not support canvas.
</canvas>
</div>
<!-- ^ End Canvas -->
</body>
</html>
And here's my CSS:
#canvasOne {
background-color: #cccccc;
border: 10px solid rgba(136, 128, 172, 0.9);
margin-left: 210px;
margin-right: auto;
margin-top: 130px;
#body {
background-image: url("mansion.jpg");
background-repeat: no-repeat;
}
Honestly, if someone could just help me put an image in the canvas and make it so that certain areas where the mouse hovers over a text box would appear, would be awesome. The idea is that it's a game where you "look" around the room with your mouse for clues. And once again, I'm very new to this so sorry if this is formatted weird or my question is too ridiculously long.
I'm not sure what exactly you want but i fixed the problem where the image is not coming up on the canvas.
The problem is that on your CSS you are coloring the background then you are also putting the image on it causing it to overlap.
Here is the CSS code that I have changed:
#canvasOne {
background-image: url("mansion.jpg");
background-repeat: no-repeat;
border: 10px solid rgba(136, 128, 172, 0.9);
margin-left: 210px;
margin-right: auto;
margin-top: 130px;
}
I dont know how to do the hover part but you should look into this
This is your main problem:
window.addEventListener("load",eventWindowLoaded, false);
The reason I say that is because you are calling the evenWindowLoaded function once -- when the page initially loads. Since this is the case, whatever state the drawLines() and other functions are in when the page loads for the first time, that will be draw on the canvas.
Instead you should try to use this:
var timer = setInterval(function() { eventWindowLoaded(); }, 100);
and then clear the canvas and re-draw it.
(this is for the hover effect)
that way, you can do calculate if the mouse's cursor is above a particular space on the canvas and then do whatever functions if it is... this isn't 100% going to work, but its a general idea of what you could do:
var mousePos;
var timer = setInterval(function() { eventWindowLoaded(); }, 100);
function eventWindowLoaded() {
context.clearRect(0,0,width,height);
for (var i=0; i<images.count; ++i) {
var img = images[i];
if (Math.Abs(mousePos.x - img.Pos().x)) <= img.width) {
if (Math.Abs(mousePos.y - img.Pos().y)) <= img.height) {
do_hover_event();
}
}
}
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
canvas.addEventListener('mousemove', function(evt) {
mousePos = getMousePos(canvas, evt);
}
Thats one thing -- here's another:
You are leaving the scope of the variable definition for the canvas/context var's, try this method for the canvas/context -- using 3 diffeerent separate functions and defining the width, height, theCanvas, and context all in the global scope
var width=1000;
var height=450;
var theCanvas = document.getElementById("canvasOne");
var context = theCanvas.getContext("2d");
function canvasApp() {
if (!canvasSupport()) {
return;
}
gameLoop();
}
function drawCanvas(){
context.fillStyle="teal";
context.fillRect(0,0,width,height);
setColor();
drawLines();
}
function gameLoop(){
requestAnimationFrame(gameLoop);
drawCanvas();
}

Autoresize text to fill fixed size container using HTML only

Needing a solution to autoresize text in a fixed sized container. A single word should appear really large filling the container. The longer the string the smaller the font becomes as it resizes to fit on one line.
The code I've found (see below) is almost there but for some reason wraps the text onto a second line. Any suggestions on how I could fix it so no matter how long the string of text it will resize and always be just a single line of text?
Thanks
<html>
<head>
<style type="text/css">
#dynamicDiv
{
background: #CCCCCC;
width: 240px;
height: 64px;
font-size: 64px;
overflow: hidden;
}
</style>
<script type="text/javascript">
function shrink()
{
var textSpan = document.getElementById("dynamicSpan");
var textDiv = document.getElementById("dynamicDiv");
textSpan.style.fontSize = 64;
while(textSpan.offsetHeight > textDiv.offsetHeight)
{
textSpan.style.fontSize = parseInt(textSpan.style.fontSize) - 1;
}
}
</script>
</head>
<body onload="shrink()">
<div align='center' id="dynamicDiv"><span id="dynamicSpan">Here is a string of text I want on just one line</span></div>
</body>
</html>
This code works, but I am using a little jQuery, I hope this helps in some way...
<style type="text/css">
#container {
height:100px;
background-color:#eeeeee;
text-align:center;
font-family:Myriad Pro;
}
<style>
<div id="container">01234567890123456789</div>
<script type="text/javascript">
$(document).ready(function()
{
var w = parseInt($("#container").width());
var l = parseInt($("#container").html().length);
var fontSize = ( (w / l) * 2 ) - 2;
fontSize = fontSize+'px';
$("#container").css('font-size', fontSize);
});
</script>

html5 - drag a canvas

I have a huge HTML5 Canvas, and I want it to work like google maps: the user can drag it and see only a small part of it (the screen's size) all the time. it renders only the part you can see on the screen.
how can I do it? do you have an idea?
2 simple steps:
place the canvas inside a div container with overflow:hidden
use any method to make your canvas draggable (I will use jQuery UI)
To follow my method you need to go to the jQuery UI website and download any version of the jQuery UI (you can create a custom version only consisting of the UI Core and Draggable Interaction for this example.)
Unpack the .zip file and move the 'js' folder to your page directory.
Inlcude the .js files contained in the folder into your page.
Place the following code between your <head></head>-tags to get your canvas draggable:
<script type="text/javacript">
$(function() {
$("#CanvasID").draggable();
});
</script>
Here's an example:
<!DOCTYPE>
<html>
<head>
<title>canvas test</title>
<script type="text/javascript" src="js/jquery-1.5.1.min.js"></script> <!-- include the jQuery framework -->
<script type="text/javascript" src="js/jquery-ui-1.8.11.custom.min.js"></script> <!-- include JQuery UI -->
<style type="text/css">
#box{
width: 400px;
height: 400px;
border:5px solid black;
overflow:hidden;
position:relative;
} /* Just some basic styling for demonstration purpose */
</style>
<script type="text/javascript">
window.onload = function() {
var drawingCanvas = document.getElementById('myDrawing');
// Check the element is in the DOM and the browser supports canvas
if(drawingCanvas.getContext) {
// Initaliase a 2-dimensional drawing context
var context = drawingCanvas.getContext('2d');
context.strokeStyle = "#000000";
context.fillStyle = "#FFFF00";
context.beginPath();
context.arc(200,200,200,0,Math.PI*2,true);
context.closePath();
context.stroke();
context.fill();
}
// just a simple canvas
$(function() {
$( "#myDrawing" ).draggable();
});
// make the canvas draggable
}
</script>
</head>
<body>
<div id="box">
<canvas id="myDrawing" width="800" height="800">
<p>Your browser doesn't support canvas.</p>
</canvas>
</div>
</body>
</html>
Hope this get's you going.
note: This is just a basic example. This will still need some editing. For example the user can drag the canvas totally out of the viewport (perhaps constraining the Canvas to the div may do the trick?). But this should be a good starting point.
I would use two canvases. Keep your huge source canvas hidden and copy portions of it to a second smaller visible canvas. Here's my quickly hacked-up proof of concept:
<!DOCTYPE HTML>
<html>
<head>
<title>canvas scroll</title>
<style type="text/css">
body {
margin: 0;
padding: 0;
overflow: hidden;
}
#source {
display: none;
}
#coords{
position: absolute;
top: 10px;
left: 10px;
z-index: 2;
}
#coords p{
background: #fff;
}
</style>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
var $window;
var img;
var $source; var source; var sourceContext;
var $target; var target; var targetContext;
var scroll = {
x : 0,
y : 0
};
var scrollMax;
function init() {
// Get DOM elements
$window = $(window);
$source = $('canvas#source');
source = $source[0];
sourceContext = source.getContext("2d");
$target = $('canvas#target');
target = $target[0];
targetContext = target.getContext("2d");
// Draw something in source canvas
sourceContext.rect(0, 0, source.width, source.height);
var grd = sourceContext.createLinearGradient(0, 0, source.width, source.height);
grd.addColorStop(0, '#800080');
grd.addColorStop(0.125, '#4B0082');
grd.addColorStop(0.25, '#0000FF');
grd.addColorStop(0.325, '#008000');
grd.addColorStop(0.5, '#FFFF00');
grd.addColorStop(0.625, '#FFA500');
grd.addColorStop(0.75, '#FF0000');
grd.addColorStop(0.825, '#800080');
sourceContext.fillStyle = grd;
sourceContext.fill();
/*
* Setup drag listening for target canvas to scroll over source canvas
*/
function onDragging(event){
var delta = {
left : (event.clientX - event.data.lastCoord.left),
top : (event.clientY - event.data.lastCoord.top)
};
var dx = scroll.x - delta.left;
if (dx < 0) {
scroll.x = 0;
} else if (dx > scrollMax.x) {
scroll.x = scrollMax.x;
} else {
scroll.x = dx;
}
var dy = scroll.y - delta.top;
if (dy < 0) {
scroll.y = 0;
} else if (dy > scrollMax.y) {
scroll.y = scrollMax.y;
} else {
scroll.y = dy;
}
event.data.lastCoord = {
left : event.clientX,
top : event.clientY
}
draw();
}
function onDragEnd(){
$(document).unbind("mousemove", onDragging);
$(document).unbind("mouseup", onDragEnd);
}
function onDragStart(event){
event.data = {
lastCoord:{
left : event.clientX,
top : event.clientY
}
};
$(document).bind("mouseup", event.data, onDragEnd);
$(document).bind("mousemove", event.data, onDragging);
}
$target.bind('mousedown', onDragStart);
/*
* Draw initial view of source canvas onto target canvas
*/
$window.resize(draw);
$window.trigger("resize");
}
function draw() {
target.width = $window.width();
target.height = $window.height();
if(!scrollMax){
scrollMax = {
x: source.width - target.width,
y: source.height - target.height
}
}
targetContext.drawImage(source, scroll.x, scroll.y, target.width, target.height, 0, 0, target.width, target.height);
$('#x').html(scroll.x);
$('#y').html(scroll.y);
}
$(document).ready(init);
</script>
</head>
<body>
<div id="coords">
<p>Drag the gradient with the mouse</p>
<p>x: <span id="x"></span></p>
<p>y: <span id="y"></span></p>
</div>
<canvas id="source" width="4000" height="4000"></canvas>
<canvas id="target"></canvas>
</body>
</html>