我正在使用jQuery滑块将我的图像颜色从蓝色变为红色(范围为-100到100),通过着色实现。这意味着当滑块值为0时,图像应该看起来正常(默认状态),并根据滑块的值从蓝色(-100)到(100)进行更改。
在本地环境中,我能够将图像加载到画布中(由于某种原因,在jsfiddle上无法加载图像)。
主要问题是当前代码不能按预期修改颜色。
请看一下。
在本地环境中,我能够将图像加载到画布中(由于某种原因,在jsfiddle上无法加载图像)。
主要问题是当前代码不能按预期修改颜色。
http://jsfiddle.net/q3qw1c0o/3/
$(function(){
var currentValue = $('#currentValue');
$( "#slider" ).slider({
range: "max",
min: -100,
max: 100,
value: 0,
slide: function( event, ui ) {
$( "#sliderValue" ).val( ui.value );
$(ui.value).val($('#sliderValue').val());
changeIt(ui.value);
}
});
$("#sliderValue").change(function() {
$("#slider").slider("value" , $(this).val())
});
});
var x; //drawing context
var width;
var height;
var fg;
var buffer
window.onload = function() {
var drawingCanvas = document.getElementById('myDrawing');
// Check the element is in the DOM and the browser supports canvas
if(drawingCanvas && drawingCanvas.getContext) {
// Initaliase a 2-dimensional drawing context
x = drawingCanvas.getContext('2d');
width = x.canvas.width;
height = x.canvas.height;
fg = new Image();
fg.src = 'http://icons.iconarchive.com/icons/iconshow/transport/256/Sportscar-car-icon.png';
// to tint the image, draw it first
x.drawImage(fg,0,0);
}
}
function changeIt(value) {
// create offscreen buffer,
buffer = document.createElement('canvas');
buffer.width = fg.width;
buffer.height = fg.height;
bx = buffer.getContext('2d');
// fill offscreen buffer with the tint color
bx.fillStyle = 'rgb(' + value + ', 0, ' + (255 - value) + ')';
bx.fillRect(0,0,buffer.width,buffer.height);
// destination atop makes a result with an alpha channel identical to fg, but with all pixels retaining their original color *as far as I can tell*
bx.globalCompositeOperation = "destination-atop";
bx.drawImage(fg,0,0);
//then set the global alpha to the amound that you want to tint it, and draw the buffer directly on top of it.
x.globalAlpha = 0.5;
x.drawImage(buffer,0,0);
}
请看一下。