Jquery image hover, click and grayscale effect with tab and caption - javascript

i want my image get black white (grayscale) after i hover they will change to the color. it is already sucses, but i want if i click image they will change color, and show content in the div i already add .click .dblclick and .toogke function but always change image to the black and white here are the code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Tabbed Navigation</title>
<style type="text/css">
.item {
width: auto;
margin: 0 0 0 0;
float: left;
}
.item.first {
clear: left;
margin-left: 0;
}
.item img {
opacity:0;
}
.wrapper{
float:left; /* important */
position:relative; /* important(so we can absolutely position the description div */
margin-right: 20px
}
.description{
position:absolute; /* absolute position (so we can position it where we want)*/
bottom:50px; /* position will be on bottom */
width:100%;
/* styling bellow */
background-color:black;
font-family: 'tahoma';
font-size:15px;
color:white;
opacity:0.6; /* transparency */
filter:alpha(opacity=60); /* IE transparency */
z-index: 9999;
}
p.description_content{
padding:5px;
margin:0px;
}
.item img a:active {
background-image: url(images/icondock.jpg);
}
</style>
<script src="jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
// $(".item img").css({"display":"none");
// On window load. This waits until images have loaded which is essential
$(window).load(function(){
// Fade in images so there isn't a color "pop" document load and then on window load
$(".item img").animate({opacity:1},500);
// clone image
$('.item img').each(function(){
var el = $(this);
el.css({"position":"absolute"}).wrap("<div class='img_wrapper' style='display: inline-block'>").clone().addClass('img_grayscale').css({"position":"absolute","z-index":"998","opacity":"0"}).insertBefore(el).queue(function(){
var el = $(this);
el.parent().css({"width":this.width,"height":this.height});
el.dequeue();
});
this.src = grayscale(this.src);
});
// Fade image
$('.item img').mouseover(function(){
$(this).parent().find('img:first').stop().animate({opacity:1}, 500);
})
$('.img_grayscale').mouseout(function(){
$(this).stop().animate({opacity:0}, 500);
});
});
// Grayscale w canvas method
function grayscale(src){
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var imgObj = new Image();
imgObj.src = src;
canvas.width = imgObj.width;
canvas.height = imgObj.height;
ctx.drawImage(imgObj, 0, 0);
var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
for(var y = 0; y < imgPixels.height; y++){
for(var x = 0; x < imgPixels.width; x++){
var i = (y * 4) * imgPixels.width + x * 4;
var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
imgPixels.data[i] = avg;
imgPixels.data[i + 1] = avg;
imgPixels.data[i + 2] = avg;
}
}
ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
return canvas.toDataURL();
}
</script>
</head>
<body>
<div class='wrapper'>
<div class="item">
<img src="images/icondock.jpg" />
</div>
<div class="description">
<p class="description_content">The pack, the basic The pack, the basic More » </p>
</div>
</div>
<div class='wrapper'>
<div class="item">
<img src="images/koifish.jpg" />
</div>
<div class="description">
<p class="description_content">The pack, the basic The pack, the basic More » </p>
</div>
</div>
<div class='wrapper'>
<div class="item">
<img src="images/sakura.jpg" />
</div>
<div class="description">
<p class="description_content">The pack, the basic The pack, the basic More » </p>
</div>
</div>
</body>
</html>
if it is so hard you can use 2 images grayscale and color

javascript:
$(function(){
var canv = document.createElement('canvas'),
ctx = canv.getContext('2d');
canv.style.cssText = "position:absolute;left:-10000px;";
document.body.appendChild( canv );
function getGrayScale(src, el ){
$("<img src=\""+src+"\" />").appendTo("body").bind("load", function ( ) {
var w = canv.width = this.offsetWidth,
h = canv.height = this.offsetHeight;
ctx.drawImage( this, 0, 0);
var imgPixels = ctx.getImageData(0, 0, w, h);
for(var y = 0; y < imgPixels.height; y++){
for(var x = 0; x < imgPixels.width; x++){
var i = (y * 4) * imgPixels.width + x * 4;
var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
imgPixels.data[i] = avg;
imgPixels.data[i + 1] = avg;
imgPixels.data[i + 2] = avg;
}
}
ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
$("<img class = \"img_grayscale\" src=\""+ canv.toDataURL() +"\" alt=\"\" />")
.insertBefore(el)
$(this).remove();
})
}
$(".item img").each(function(){
getGrayScale(this.src, $(this));
})
$(".item").delegate( ".img_grayscale", "mouseenter", function ( ) {
$(this).stop().animate({opacity:0}, 500)
}).delegate( ".img_grayscale","mouseout", function(){
$(this).stop().animate({opacity:1}, 500);
}).delegate( ".img_grayscale","click", function(){
$(this).remove();
});
});
add css:
.img_grayscale{ position:absolute;top:0;left:0;}
remove css:
.item img {opacity:0;}
i cant figure out what's wrong but this seems work as you expect

Related

Canvas - When i put <canvas> in div does not work

I want a draw something canvas tag , when i put in div it doesnt work. I taked this code from github. it isnot working within div.
github url => https://github.com/GeekLaunch/simple-drawing-web-app
how can i do this ? actually i dont know canvas library. but this codes enough for me. In my project i use bootstrap css library.
var canvas, ctx,
brush = {
x: 0,
y: 0,
color: '#000000',
size: 10,
down: false,
},
strokes = [],
currentStroke = null;
function redraw() {
ctx.clearRect(0, 0, canvas.width(), canvas.height());
ctx.lineCap = 'round';
for (var i = 0; i < strokes.length; i++) {
var s = strokes[i];
ctx.strokeStyle = s.color;
ctx.lineWidth = s.size;
ctx.beginPath();
ctx.moveTo(s.points[0].x, s.points[0].y);
for (var j = 0; j < s.points.length; j++) {
var p = s.points[j];
ctx.lineTo(p.x, p.y);
}
ctx.stroke();
}
}
function init() {
canvas = $('#draw');
ctx = canvas[0].getContext('2d');
function mouseEvent(e) {
brush.x = e.pageX;
brush.y = e.pageY;
currentStroke.points.push({
x: brush.x,
y: brush.y,
});
redraw();
}
canvas.mousedown(function (e) {
brush.down = true;
currentStroke = {
color: brush.color,
size: brush.size,
points: [],
};
strokes.push(currentStroke);
mouseEvent(e);
}).mouseup(function (e) {
brush.down = false;
mouseEvent(e);
currentStroke = null;
}).mousemove(function (e) {
if (brush.down)
mouseEvent(e);
});
$('#save-btn').click(function () {
window.open(canvas[0].toDataURL());
});
$('#undo-btn').click(function () {
strokes.pop();
redraw();
});
$('#clear-btn').click(function () {
strokes = [];
redraw();
});
$('#color-picker').on('input', function () {
brush.color = this.value;
});
$('#brush-size').on('input', function () {
brush.size = this.value;
});
}
$(init);
body {
margin: 0;
}
.top-bar {
display: flex;
flex-direction: row;
background-color: #3af;
border-bottom: 2px solid black;
position: absolute;
width: 100%;
}
.top-bar * {
margin: 5px 10px;
}
#draw {
display: block;
}
:<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="top-bar">
<button id="save-btn">Save</button>
<button id="undo-btn">Undo</button>
<button id="clear-btn">Clear</button>
<input type="color" id="color-picker"></input>
<input type="range" id="brush-size" min="1" nax="50" value="10"></input>
</div>
<div style="border:1px solid red;width:500px;height:500px;margin:auto;">
<canvas id="draw" style="border:1px solid red;"></canvas>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="draw.js"></script>
</body>
</html>
From my observation, the save button is not working on chrome. Because apparently Google Chrome has removed support for top-frame navigation, you can see more informations here: https://groups.google.com/a/chromium.org/forum/#!topic/blink-dev/GbVcuwg_QjM
You may try to render the canvas data to an iFrame.
Add below function to your draw.js file:
function debugBase64(base64URL){
var win = window.open();
win.document.write('<iframe src="' + base64URL + '" frameborder="0" style="border:0; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%;" allowfullscreen></iframe>');
}
Now run the function when click event occurred.
$('#save-btn').click(function () {
debugBase64(canvas[0].toDataURL());
});
Hope it works !

HTML5 canvas animation not showing background image

I'm trying to do a simple animation where a bubble rises in a beer bottle and struggling with the background image. The beer image is not showing up. I only see the bubble rising.
My code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style.css" />
<title>Bieranimation</title>
</head>
<body>
<div id="container">
<img class='img' src="https://i.imgur.com/VW3zcXq.jpg" alt="" />
<canvas id="bier" width="400" height="520" style="border:solid 1px">
</canvas>
</div>
<script type="text/javascript">
var c=document.getElementById("bier");
var ctx=c.getContext("2d");
var width = c.width; // Canvas Grösse
var heigth = c.height;
var x, y; // aktuelle x- und y-Koordinaten
var x0 = 50; // Start-Koordinaten
var y0 = 400;
var v0x = 0.05; // Geschwindigkeit in Pixel/Millisekunde
var v0y = 0.00005;
var dt = 20; // Zeitintervall in Millisekunden
var r = 40; // Radius
var zeit; // Aktuelle Laufzeit
var i = 0;
fZeichnen(ctx);
var aktiv = setInterval(function() {fZeichnen(ctx); }, dt);
function fZeichnen(context) {
// Für das Fade Out: Definition eines Alpha-Wertes
// für das Übermalen des vorhergehenden Bildzustandes
// Überdeckung 10%
// Vorhergehender Bildzustand wird mit der Füllfarbe und dem
// soeben definierten Alpha-Wert übermalt
context.fillRect(0,0,width,heigth);
// Die Ball-Zeichnung soll alles darunter liegende vollständig überdecken
// Überdeckung 100%
context.fillStyle="#FFFFFF"; // Grün
context.beginPath();
context.arc(x, y, r, 0, Math.PI*2, true);
context.closePath();
context.stroke();
// Kreis zeichnen und füllen
x = x0 + v0x; // Neue Koordinaten
y = y0 + v0y - zeit;
i += 0.1;
zeit = i * dt; // Gesamtlaufzeit
if (zeit >= 5000) {
clearInterval(aktiv)
}
}
</script>
</body>
</html>
I tried to do something with the z-index but it doesn't seem to work:
body{text-align: center;}
.img{position:absolute;z-index:-1;}
#container{
display:inline-block;
width: 400px;
height:520px;
margin: 0 auto;
position:relative;
}
#gameCanvas{
position:relative;
z-index:20;
}
I'd appreciate any kind of help.
(I'm not sure why I habitually try to answer questions in comments. Correcting that now.)
Canvases are transparent by default, but currently you're erasing your canvas each loop by filling it with white:
context.fillRect(0,0,width,heigth);
If you instead erase it (technically, fill it with a transparent color), you'll be able to see the elements stacked behind the canvas:
context.clearRect(0,0,width,heigth);

Javascript make an image bounce around screen

I have made code for a bouncing ball (using the arc() method on a canvas). I am wondering how to make an image bounce around the screen. Here is my previous code (note that the launchBall() function is going to be the function that runs the bouncing image):
<!DOCTYPE HTML>
<html>
<body onload="startBall()" oncontextmenu="return false;" style="cursor: none; overflow: hidden;">
<center>
<div id="div" style="width: 1600px; height: 700px; border: 2px solid #000000; background-color: grey;">
<br>
<img draggable="false"id="image" style="position: absolute;" width="50" height="50"src="http://www.clker.com/cliparts/b/a/b/0/1207156679935151925noxin_crosshairs.svg.hi.png"/>
</div>
<center>
<p>Score: <a>0</a></p>
</center>
<script>
var dx = 3;
var dy = 3;
var x = 100;
var y = 100;
var radius = 20;
var interval;
function startBall(){
interval = setInterval(launchBall, 20);
}
function launchBall(){
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, 1275, 695);
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * Math.PI);
ctx.fillStyle = "red";
ctx.fill();
document.getElementById
if(x<20 || x>1255) dx=-dx;
if(y<20 || y>675) dy=-dy;
x = x + dx;
y = y + dy;
}
document.getElementById("div").onmousemove = function(e) {
document.getElementById("image").style.top = e.pageY -25 + "px";
document.getElementById("image").style.left = e.pageX -25 +"px";
}
</script>
</body>
</html>

How to use <li> instead of <div> to make the tool-tip code workable?

Following is a reference fiddle:
http://jsfiddle.net/66nLy/12/
Just like this fiddle I want to implement the same functionality into a webpage where <li> is used instead of <div>.
The HTML code is as follows:
<table class="base-table selection-table" width="100%" border="0" cellspacing="0" cellpadding="0" style="margin-top:15px;">
<tr class="evenRow" id="37261">
<td class="question">
<ul class="tabl-head">
<li>Question 1.</li>
<li class="center-align">**Report question issue - QUE37261**</li>
<li class="right-align"><a class="change_ps_question" href="change_practice_sheet_question.php?question_id=37261&practice_sheet_id=3"><label class="bright" style="cursor:pointer;" >Change Question</label></a>
</li>
</ul>
<ul class="options w-auto">
<li><strong>Question:</strong>
Pair of contrasting characters controlling the same trait is called:</li>
<li><strong>Answer:</strong>
<p><b style="font-size:13px;">1.</b> Factors
<br />
</p>
<p><b style="font-size:13px;">2.</b> alleles
<br />
</p>
<p><b style="font-size:13px;">3.</b> alloloci
<br />
</p>
<p><b style="font-size:13px;">4.</b> paramorphs
<br />
</p>
</li>
<li><strong>Correct Answer Option : 2</strong>
</li>
</ul>
</td>
</tr>
</table>
The actual table is too large and contains many records. For brevity I have shown only one record.
Here is what you want buddy: http://jsfiddle.net/webcarvers/66nLy/17/
HTML:
<li class='tooltip'>
<img src='http://www.craiglotter.co.za/wp-content/uploads/2009/12/craig_question_mark_icon1.png' alt='Help' />
<ul class="tooltipText">
<li class='info'>Some text to fill the box with.</li>
</ul>
</li>
css:
li{
display:block;
}
li.tooltip
{
position:relative;
display:inline-block;
cursor:pointer;
width:300px;
text-align:right;
}
li.tooltip > ul li.info
{
display:none;
}
li.tooltip > ul li.info_container
{
position:absolute;
right:20px;
width:200px;
height:100px;
display:none;
color:#000;
}
li.tooltip ul li.info
{
text-align:left;
position:absolute;
left:1px;
right:1px;
top:20px;
bottom:1px;
color:#000;
padding:5px;
overflow:auto;
border:1px solid #000;
}
JS:
"use strict";
function click(event) {
var elem = this.parentNode.querySelector('.info_container');
if (elem)
elem.style.display = elem.style.display === 'block' ? 'none' : 'block';
}
function toolify() {
var idx,
len,
elem,
info,
text,
elements = document.querySelectorAll('li.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('li');
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
console.log(elements.length);
for (idx = 0, len = elements.length; idx < len; ++idx) {
elem = elements[idx];
elem.querySelector('img').addEventListener('click', click);
text = elem.querySelector('ul li.info');
// Create a new div element, and place the text and pointer in it
info = document.createElement('li');
text.parentNode.replaceChild(info, text);
info.className = 'info_container';
info.appendChild(pointer.cloneNode());
info.appendChild(text);
text.style.display = 'block';
//info.addEventListener('click',click);
}
}
window.addEventListener('load', toolify);
You can try this:-
HTML changes
<ul>
<li class='info'>
Some text to fill the box with........
</li>
</ul>
Script Changes
text = elem.querySelector('li.info');
CSS Changes
div.tooltip > li.info
{
display:none;
}
div.tooltip li.info
{
text-align:left;
position:absolute;
left:1px;
right:1px;
top:20px;
bottom:1px;
color:#000;
padding:5px;
overflow:auto;
border:1px solid #000;
}

Dynamically place Unicode characters in a div with background image

I have an image that represents a weight-lifting bar:
I want to put the Full Block Unicode character (e.g. representing plates) on both the left and the right sides of the bar.
I'm trying to do this with 3 divs:
Barbell left: plates that go on the left side of the bar, right-justified
Barbell middle: nothing left blank
Barbell right: plates that go on the right side of the bar, left-justified
Here is a professional representation of the divs with a plate:
I thought I could do this with floats and percentages on div widths, but I'm not having any luck.
Here is my most recent attempt on js fiddle.
UPDATE
I got the answer I wanted, but based on the comment, I discovered that using Canvas was the better route.
I was able to achieve a better result with this html:
<div data-role="page" id="p1">
<div data-role="header"><h1>Header Page 1</h1></div>
<div data-role="content">
<div class="bar-canvas">
<canvas id="_barCanvas"></canvas>
</div>
</div>
</div>
<div data-role="footer"><h4>Footer</h4></div>
</div>
and this js:
var WIDTH_FACTOR = .8; //80% of screen size
var HEIGHT_FACTOR = .1; //10% of height size
var WEIGHT_SPACER = 2;
var ctx = $("#_barCanvas")[0].getContext("2d");
ctx.canvas.width = (window.innerWidth * WIDTH_FACTOR);
ctx.canvas.height = (window.innerHeight * HEIGHT_FACTOR);
var bar_width = ctx.canvas.width * .8;
var bar_height = ctx.canvas.height * .1;
var bar_x = (ctx.canvas.width - bar_width)
var bar_y = (ctx.canvas.height * .5)
var plate_stop_width = bar_width * .01;
var plate_stop_height = bar_height * 4;
var plate_stop_y = bar_y - ((plate_stop_height - (bar_y / 2)));
var rubber_plate_height = bar_height * 8;
var rubber_plate_y = (ctx.canvas.height / 2) - (rubber_plate_height/2) + (bar_height/2);
var small_plate_height = plate_stop_height;
var small_plate_y = plate_stop_y;
var left_plate_stop_x = bar_x + (bar_width * .3);
var right_plate_stop_x = bar_x + (bar_width * .7);
//Draw Bar
ctx.fillStyle = "black";
ctx.fillRect (bar_x, bar_y, bar_width, bar_height);
//Draw Plate stop left
ctx.fillStyle = "black";
ctx.fillRect (left_plate_stop_x, plate_stop_y, plate_stop_width, plate_stop_height);
//Draw Plate stop right
ctx.fillStyle = "black";
ctx.fillRect (right_plate_stop_x, plate_stop_y, plate_stop_width, plate_stop_height);
//Draw 45 lb Plates
var plate_width = bar_width * .04;
var current_plate_height = 0;
ctx.fillStyle = 'red';
ctx.fillRect(left_plate_stop_x - plate_width, rubber_plate_y, plate_width, rubber_plate_height);
ctx.fillStyle = 'red';
ctx.fillRect(right_plate_stop_x + plate_stop_width, rubber_plate_y, plate_width, rubber_plate_height);
I did it changing a bit your markup and css.
Demo (tested on Chrome 22 only)
HTML:
<div data-role="page" id="p1">
<div data-role="header"><h1>Header Page 1</h1></div>
<div data-role="content">
<div class="barbell-background">
<div class="barbell-left">█</div>
<div class="barbell-right">█</div>
</div>
</div>
<div data-role="footer"><h4>Footer</h4></div>
</div>
CSS:
.barbell-background
{
font-size:3em;
line-height:1.4em;
height:1.4em;
position:relative;
background-image:url('http://i.stack.imgur.com/ZmFY4.png');
background-repeat: no-repeat;
background-position: center;
}
.barbell-left, .barbell-right
{
position:absolute;
color:red;
}
.barbell-left
{
right:50%;
margin-right:146px;
}
.barbell-right
{
left:50%;
margin-left:145px;
}​
As Joachim Sauer said, it's probably easier and more consistent to just use divs for the red squares...
Another demo
HTML:
<div data-role="page" id="p1">
<div data-role="header"><h1>Header Page 1</h1></div>
<div data-role="content">
<div class="barbell-background">
<div class="barbell-left"></div>
<div class="barbell-right"></div>
</div>
</div>
<div data-role="footer"><h4>Footer</h4></div>
</div>
CSS:
.barbell-background
{
font-size:3em;
line-height:1.3em;
height:1.3em;
position:relative;
background-image:url('http://i.stack.imgur.com/ZmFY4.png');
background-repeat: no-repeat;
background-position: center;
}
.barbell-left, .barbell-right
{
position:absolute;
background:red;
width:0.5em;
height:100%;
}
.barbell-left
{
right:50%;
margin-right:146px;
}
.barbell-right
{
left:50%;
margin-left:144px;
}​
In both demos you'll see that a pixel "wobbles". Knowing the contents of the red square i could try to fix it.

Categories