This is my first html5 project, getting the gist of it, need a bit of help. I used a jquery UI slider to send an opacity value to the canvas and it works quite nicely… but I can’t get the image to completely turn off when the slider is in the off position with a value of zero. Here is a fiddle of what I’m trying to do : http://jsfiddle.net/N6wZZ/2/
Here is my JS:
$("#slider").slider({
animate: true,
range: "min",
value: 0,
min: 0,
max: 0.9,
step: .01,
create: function (event, ui) {
var opacityValue = '0.0';
canvasFunction(opacityValue);
},
slide: function (event, ui) {
$('#hiddenField').attr('value', ui.value);
$("#slider-result").html(ui.value);
var opacityValue = $('#hiddenField').val();
if (opacityValue == 0) {
var opacityValue = 0;
var workAroundVar = 300;
var workAroundVarTwo = 0;
canvasFunction(opacityValue, workAroundVar, workAroundVarTwo);
}
else {
var workAroundVar = 0;
var workAroundVarTwo = 300;
canvasFunction(opacityValue, workAroundVar, workAroundVarTwo);
}
}
});
function canvasFunction(opacityValue, workAroundVar, workAroundVarTwo){
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var img1 = loadImage('http://moosepic.com/test2.png', main);
var img2 = loadImage('http://moosepic.com/test.png', main);
var imagesLoaded = 0;
function main() {
imagesLoaded += 1;
if (imagesLoaded == 2) {
// composite now
ctx.drawImage(img1, 0, 0, 300, 300);
ctx.globalAlpha = opacityValue;
ctx.drawImage(img2, workAroundVar, workAroundVar, workAroundVarTwo, workAroundVarTwo);
}
}
function loadImage(src, onload) {
var img = new Image();
img.onload = onload;
img.src = src;
return img;
}
}
as you can see I’ve made a bunch of workarounds to turn off the second image or just knock it out of the canvas. Any help would be awesome.
Silas. I’ve taken a look at your jsFiddle. I forked it and made some changes/improvements to your approach and I think it accomplishes your goal:
http://jsfiddle.net/3LJsX/7/
Here is the approach I took (which is pretty close to yours, just some minor differences):
refreshVisualsfunction which updates the value of the slider div and updates the canvasA main difference is in the
drawfunction which was calledcanvasFunctionin your example. In mydrawfunction, I make sure to:That should be it! Let me know if you have any questions.