Okay, I am quite new to Javascript and JQuery, but after hours and hours of research I can't help myself but ask this question.
I want to write a hoverfunction that creates a greyscale-version of an image and lies this new black-and-white image above the original. I've found a nice working code on spyrestudios.com, so my code looks like this:
HTML normal code
<!--IMG that is only an example with fixed sizes to make the script work. -->
<img id="canvasSource" class="testpic" width="480" height="321" alt="" src="canvas.jpg" title="bryom">
<!--canvas that is only a dummy to test the script, later the canvas shouldn't be fixed in the html but created by jquery dynamically -->
<canvas id="area" width="480" height="321" style="display:none"> </canvas>
and Script
<!-- fill canvas with greyscale version -->
var canvas = document.getElementById("area");
var context = canvas.getContext("2d");
var image = document.getElementsByClassName("testpic");
context.drawImage(image, 0, 0);
var imgd = context.getImageData(0, 0, 480, 321); <!--width and height are here only testnumbers because image size may change within the webpage, numbers should be replaced by variables if possible -->
var pix = imgd.data;
for (var i = 0, n = pix.length; i < n; i += 4) {
var grayscale = pix[i ] * .3 + pix[i+1] * .59 + pix[i+2] * .11;
pix[i ] = grayscale; // red
pix[i+1] = grayscale; // green
pix[i+2] = grayscale; // blue
// alpha
}
context.putImageData(imgd, 0, 0);
};
<!-- Hover Image shows canvas with black and white -->
$(document).ready(function(){
$("img").mouseover(function(){
$("canvas").css("display", "block");
});
$("img").mouseout(function(){
$("canvas").css("display", "none");
});
});
so far, so good. All the tutorials and descriptions I found (and understood) had two problems:
- I am working with wordpress, so I can't really add the canvas-container into the html-code myself. I have to create the canvas dynamically with jquery, dependent on how big the picture on the currentpage is and what kind of position it has inside its container.
2.nd problem is that they create the canvas in the normal flow, which means next to the original image. I would love the canvas to lie directly on the original image, but I have no idea how to read out size and position of the original image and use them for creating the canvas.
I guess this must be very easy, but I can't really focus out how exactly the things have to be connected in the code. I have really no idea how to start with this and I couldn't find something as simple as I need it.
Except
var img = document.getElementByClassName("testpic");
var canvas = document.createElement("canvas");
all the beginning is missing. How do I ask for the image size of any picture with the class "testpic"? How do I get the position? How do I use this creating the canvas in jquery?
I would be really thankful for help as this is my first trial to find help by a forum like this!! Thanks a lot for any help