【发布时间】:2015-05-23 06:58:58
【问题描述】:
我正在使用 jquery 滑块通过着色将图像颜色从蓝色更改为红色(范围为 -100 到 100)。这意味着当滑块值为 0 时,图像应该看起来正常(默认值),并根据滑块的值从蓝色 (-100) 更改为 (100)。
在我的本地,我可以将图像加载到我的画布中(由于某种原因,图像没有加载到 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);
}
请看一下。
【问题讨论】:
-
我运行了您提供的代码,但出现错误“theImage”未定义,您是否没有设置名为 theImage 的变量?
-
@SythnetP 抱歉刚刚编辑了帖子。这不是我刚刚错过设置正确 var 名称的问题。现已修复。
-
你知道如何在任何浏览器上使用控制台吗?我刚刚再次运行它,我得到 x.canvas.width 未定义
-
@SythnetP 我在控制台上没有收到任何错误!无论如何,我的观点是函数 changeIt 无法正常工作且无法按预期工作。你能看出问题出在哪里吗?
-
您将目标图像放在原始图层的顶部,导致您使用 globalAlpha 丢失原始像素数据。您可以为填充样式 (rgba) 使用 alpha 通道,它会让您走得更远,但我强烈建议您使用@markE 描述的像素操作。
标签: javascript jquery html jquery-ui html5-canvas