HTML5 Image Viewer (Browse Add Image) - html5-canvas

http://jsfiddle.net/KFEAC/2/
I'd like to learn how to add a image from my hard drive into an HTML5 canvas. I don't wanna upload it, just load it from my hard drive dynamically from a browse window after a button is clicked.
I do believe this is possible without PHP.
Can anyone help?
HTML:
<input type="file" id="openimg"> <input type="button" id="load" value="Load" style="width:100px;"><br/>
Width and Height (px): <input type="text" id="width" style="width:100px;">, <input type="text" id="height" style="width:100px;"><br/>
<canvas id="myimg" width="300" height="300"></canvas>
JavaScript/JQuery:
$(function(){
$("canvas#myimg").draggable();
var canvas = document.getElementById("myimg");
var context = canvas.getContext("2d");
function draw() {
var chosenimg = $("#openimg").val();
var w = parseInt($("#width").val());
var h = parseInt($("#height").val());
canvas.width = w;
canvas.height = h;
var img = new Image();
img.onload = function () {
context.drawImage(img,0,0,img.width,img.height,0,0,w,h);
}
img.src = $("#openimg").val();}
$("#width").val(150);
$("#height").val(150);
$("#load").click(function(){ draw(); });
});

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas = document.getElementById("myimg");
var context = canvas.getContext("2d");
function draw() {
var chosenimg = $("#openimg").val();
var w = parseInt($("#width").val());
var h = parseInt($("#height").val());
canvas.width = w;
canvas.height = h;
var img = new Image();
img.onload = function () {
context.drawImage(img,0,0,img.width,img.height,0,0,w,h);
console.log(img.src);
}
img.src = $("#openimg").val();
}
$("#width").val(150);
$("#height").val(150);
$("#load").click(function(){ draw(); });
}); // end $(function(){});
</script>
</head>
<body>
<input type="file" id="openimg">
<input type="button" id="load" value="Load" style="width:100px;"><br/>
Width and Height (px):
<input type="text" id="width" style="width:100px;">,
<input type="text" id="height" style="width:100px;"><br/>
<canvas id="myimg" width="300" height="300"></canvas>
</body>
</html>

Related

Change orientation of line using HTML canvas fillRect()

I want to use HTML canvas fillRect() to make a block with a diagonal line from upper right to bottom left.
I managed to create a block with a line from upper left to bottom right.
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="300" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
for(var i = 0; i < 300; ++i) {
ctx.fillRect(i, i, 1, 1);
}
</script>
</body>
</html>
How can I get what I want based on this code?
I managed it using lineTo.
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="300" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.moveTo(300, 0);
ctx.lineTo(0, 300);
ctx.moveTo(0, 300);
ctx.lineTo(300, 0);
ctx.stroke();
</script>
</body>
</html>

Drag and Drop Cordova Image

First of all, I'm using cordova.
I wanna do an application which get a picture and shows it at the screen (it's done!). Now, I need to pick some other little images, drag and drop them on the original picture, save the modifications and send to a server...
How can I do the drag and drop AND save the big image after dropped little images? (if possible, using plugins)
I saw this, but how can I save as a new image?
Drag and Drop functionality in PhoneGap?
How I did this:
HTML
<!DOCTYPE html>
<html>
<head>
<!-- meta -->
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<!-- css -->
<link rel="stylesheet" type="text/css" href="css/camera.css">
<!-- js -->
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/camera.js"></script>
<script type="text/javascript" src="js/compartilhamento.js"></script>
<!-- jQuery -->
<script type="text/javascript" src="jQuery/jquery-1.10.2.js"></script>
<!--script type="text/javascript" src="jQuery/jquery.mobile-1.4.5.min.js"></script-->
<script type="text/javascript" src="jQuery/jquery-ui.min.js"></script>
<script src="jQuery/jquery.ui.touch-punch.min.js"></script>
<!-- js drag and drop -->
<script type="text/javascript" src="js/add-aderecos.js"></script>
<script type="text/javascript" src="js/salva-canvas.js"></script>
<title></title>
</head>
<body>
<div style="" id="botoes">
<p>Voltar</p>
<p><input type="button" onClick="tiraFoto()" value="Acessar Câmera"></p>
</div>
<!--Aqui estao os objetos disponibilizados para drag-->
<div id="objetos" style="display: none;">
<p>Clique na imagem que desejar adicionar à sua foto!</p>
<img src="img/nariz.png" id="add-nariz"></img>
<hr/>
</div>
<!--Pega as dimensoes da foto vinda da camera/galeria e posteriormente é cópia do canvas, para que possa ser compartilhado via social-x-sharing plugin-->
<img id="pegaDim" src="" style="display: none;"></img>
<!--aqui está a foto tirada, com redimensionamento via CSS. Aqui acontece a edicao da imagem-->
<div id="box-foto">
<img src="" id="imagemCamera" style="display: none;"></img>
</div>
<!--pra cá será copiada a imagem editada-->
<canvas id="myCanvas" style="display: none;"></canvas>
<!--botoes-->
<div id="compartilhamento" style="display: none;">
<p><input type="button" value="Salvar Mudanças" id="salvaImagem"/></p>
<p><input type="button" onclick="imagemTeste('pegaDim');" value="Compartilhar Imagem" /></p>
</div>
</body>
</html>
camera.js
function tiraFoto() {
navigator.camera.getPicture(onSuccess, onFail,
{
destinationType : Camera.DestinationType.FILE_URI,
sourceType : Camera.PictureSourceType.CAMERA
}
);
}
function onSuccess(imageData) {
//pega DOM
var compartilha = document.getElementById('compartilhamento');
var botoes = document.getElementById('botoes');
var pegaDim = document.getElementById('pegaDim');
var image = document.getElementById('imagemCamera');
var objetos = document.getElementById('objetos');
//aparece depois da foto
objetos.style.display = 'block';
pegaDim.src = imageData;
image.src = imageData;
image.style.display = 'block';
compartilha.style.display = 'block';
botoes.style.display = 'none';
}
function onFail(message) {
alert('Erro: ' + message);
}
add-aderecos.js
$(document).on('click', '#add-nariz', function(){
var a = $('#add-nariz');
var src = a.attr('src');
var elem = $('<img class="objetos" src="' + src + '" width="30px" height="30px" style="positon: relative;" />');
$('#box-foto').append(elem);
elem.draggable();
});
salva-canvas.js
$(document).on('click', '#salvaImagem', function(){
//pega dimensoes originais da foto da camera/galeria
var dimensoesOriginais = document.getElementById('pegaDim');
var larguraOriginal = dimensoesOriginais.width;
var alturaOriginal = dimensoesOriginais.height;
//pega a imagem que aparece na tela e o canvas
var m = $('#imagemCamera');
var totX = parseInt(m.css('width'));
var totY = parseInt(m.css('height'));
var c = document.getElementById('myCanvas');
c.width = totX;
c.height = totY;
var ctx = c.getContext('2d');
//alert(totX + '\n' + totY);
var base = m[0];
//drawImage(imagem,comecaCorteX,comecaCorteY,paraCorteX,paraCorteY,X,Y,Largura,Altura)
ctx.drawImage(base,0,0,larguraOriginal,alturaOriginal,0,0,totX,totY);
var posicoes = [];
$(".objetos").each(function(){
var img = $(this);
x = parseInt(img.css("left"))+totX;
y = parseInt(img.css("top"))+totY;
altura = parseInt(img.css("width"));
largura = parseInt(img.css("height"));
posicoes.push([
x,
y,
largura,
altura,
]);
});
//alert( JSON.stringify(posicoes));
//pega a imagem do nariz -- palheativo
var copiasNariz = $('#add-nariz')[0];
//loop pra canvas
var j;
var numAderecos = posicoes.length;
for(j = 0; j < numAderecos; j++){
//drawImage(imagem,comecaCorteX,comecaCorteY,paraCorteX,paraCorteY,X,Y,Largura,Altura)
ctx.drawImage(copiasNariz,posicoes[j][0]-156+(j*posicoes[j][2]),posicoes[j][1],posicoes[j][2],posicoes[j][3]);
alert('posicao inicial: ' + posicoes[j][0] + '\n\nposicao final: ' + posicoes[j][0]-156+(j*posicoes[j][2]) + '\n\nvariacao de :' + (-156+(j*posicoes[j][2])));
}
//Esconde a foto original e mostra o canvas
var some = document.getElementById('box-foto');
c.style.display = "block";
some.style.display = "none";
//esconde os objetos arrastaveis
$('#objetos')[0].style.display = "none";
//faz uma copia do canvas como src de uma tag img -- vai pro pegaDim
var finalImageToShare = new Image();
var srcFinal = finalImageToShare.src;
srcFinal = c.toDataURL();
dimensoesOriginais.src = srcFinal;
});
compartilhamento.js
function imagemTeste(idTag) {
var tag = document.getElementById(idTag);
var img = tag.src;
window.plugins.socialsharing.share('Imagem compartilhada via aplicativo X.', 'Assunto (caso envie por email)', img, null);
}
I really sorry for the portuguese ids, classes and the names of variables or functions, but I'm afraid when I change to english forgot something and this stops working. So I copied the code as it is in my real project.
I believe my code is "ugly" and longer than necessary, but I'm not so good with javaScript yet.

get viewdatadictionary value in partial view

I have a partial view in which I am trying to get the values from the parent view.
This is what I am trying:
#Html.Partial("Shared", "Home", new ViewDataDictionary { { "9595959", "8sd8sds8das8d" } })
And this is the partial view:
<!-- Google Code for apply Conversion Page --> <script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = "viewdata-number1";
var google_conversion_language = "en";
var google_conversion_format = "2";
var google_conversion_color = "ffffff";
var google_conversion_label = "viewdata-number2"; var google_conversion_value = 0;
/* ]]> */
</script>
<script type="text/javascript"
src="https://www.googleadservices.com/pagead/conversion.js">
</script>
<noscript>
<div style="display:inline;">
<img height="1" width="1" style="border-style:none;" alt=""
src="https://www.googleadservices.com/pagead/conversion/viewdata-number1/?value=0&label=viewdata-number2&guid=ON&script=0"/>
</div>
</noscript>
Is it possible to get the value straight away? I don't have any model or controller assigned to the partial view.
Thx in advance, Laziale
Updated Code:
#{
var variable = ViewData["First"];
<!-- Google Code for apply Conversion Page --> <script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = variable;
var google_conversion_language = "en";
var google_conversion_format = "2";
var google_conversion_color = "ffffff";
var google_conversion_label = "f6vICKTT6gMQzNOf3gM"; var google_conversion_value = 0;
/* ]]> */
</script>
<script type="text/javascript"
src="https://www.googleadservices.com/pagead/conversion.js">
</script>
<noscript>
<div style="display:inline;">
<img height="1" width="1" style="border-style:none;" alt=""
src="https://www.googleadservices.com/pagead/conversion/1002957260/?value=0&label=f6vICKTT6gMQzNOf3gM&guid=ON&script=0"/>
</div>
</noscript>
}
You think that will work?
Sorry i don't understan your question quite well. You can get ViewData values in partial like this:
var a = (int)ViewData["9595959"]; // variable a will get value "8sd8sds8das8d"
You can also create new ViewDataDictionary extending current view ViewDataDictionary like this:
#Html.Partial("Shared", "Home", new ViewDataDictionary(ViewData) { { "9595959", "8sd8sds8das8d" } })
it will work like this:
#{
var variable = (int)ViewData["First"];
}
<!-- Google Code for apply Conversion Page --> <script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = #variable;
var google_conversion_language = "en";
var google_conversion_format = "2";
var google_conversion_color = "ffffff";
var google_conversion_label = "f6vICKTT6gMQzNOf3gM"; var google_conversion_value = 0;
/* ]]> */
</script>
<script type="text/javascript" src="https://www.googleadservices.com/pagead/conversion.js">
</script>
<noscript>
<div style="display:inline;">
<img height="1" width="1" style="border-style:none;" alt=""
src="https://www.googleadservices.com/pagead/conversion/1002957260/?value=0&label=f6vICKTT6gMQzNOf3gM&guid=ON&script=0"/>
</div>
</noscript>
link
Here is an example of someone doing the same thing I think you're wanting to do.
Also, within your partial, just do ViewData["9595959"] to hook into that specific data.

How to center an image in the viewport with unknown height?

I'm creating an image gallery using BxSlider (http://bxslider.com) and would like to center the image both horizontally and vertically in the viewport. I am also using a resizing script so don't know the dimensions of my images.
I have tried all kinds of scripts that I've found through Google but nothing seems to be working.
This is my html:
<div id="myDiv">
<div><img src="" /></div>
<div><img src="" /></div>
<div><img src="" /></div>
</div>
My BxSlider code:
<script src="https://raw.github.com/wandoledzep/bxslider/master/jquery.bxSlider.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#myDiv').bxSlider({
mode: 'fade',
captions: true,
});
});
</script>
And my resizing code:
function resizeImg() {
var h = $(window).height();
if (840 > h) {
var bw = h - 210;
$('img').attr('height',bw);
//alert('Height: '+h);
// post-container-image
}
}
jQuery(document).ready(function(){
var h = $(window).height();
if (840 > h) {
resizeImg();
}
});
$(window).resize(function(){
var h = $(window).height();
if (840 > h) {
resizeImg();
}
});

HTML5 Canvas | How can I make this work smoother and better?

I am trying to create a wave animation in my canvas, but it works really slowly (Probably because of bad code).
How can I make this work smoother, and make the Wave(Math.sin) look more like a sea wave?
Here is the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>HTML 5 site</title>
<style>
#canvas{
margin:0 auto;
}
*{
overflow:hidden;
}
</style>
<script src="jquery-1.6.4.min.js"></script>
</head>
<body>
<div id="warp">
<canvas id="canvas" style="border:1px solid black;" />
Your Browser does not support HTML5;
</canvas>
</div>
<script>
$(document).ready(function(){
resizeCanvas();
function resizeCanvas() {
$("#canvas")
.attr('width', $(window).width())
.attr('height', $(window).height());
}
$(window).resize(resizeCanvas());
x=0;y=0;
var ctx = $("#canvas").get(0).getContext('2d');
$('#canvas').mousemove(function(e){
resizeCanvas();
for(var i=0;i<=$(window).width();i++){
y =Math.sin((i+x)*50)*12;
ctx.fillStyle = "blue";
ctx.arc(i, y+100, 4, 0, 2*Math.PI);
ctx.fill();
}
x+=20;
});
});
</script>
</body>
</html>
I changed the code quite a bit, removed the dependency for jQuery. The main thing however that I did to speed up your code was move the fill to be called only once after the draw operations, and start/end the drawing of the path. Also I was confused by the recalling of resizeCanvas() I would just tie that to the window.onresize event and just set the canvas to the innerwidth/innerheight of the window.
Live Demo
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
x=0,y=0;
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
canvas.onmousemove= function(e){
//clear the canvas
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillStyle = "blue";
var width = window.innerWidth;
// start the path
ctx.beginPath();
//draw it
for(var i=0;i<=width;i++){
y=Math.sin((i+x)*50)*12;
ctx.arc(i, y+100, 4, 0, 2*Math.PI);
}
//close it
ctx.closePath();
//fill it
ctx.fill();
x+=20;
}

Resources