【发布时间】:2012-04-24 15:32:44
【问题描述】:
我正在使用context-blender对html背景图像的前192个像素应用固定颜色的乘法效果,以实现页面标题的透明效果。
在 html 上,我有 2 个画布。一个用于应用乘法效果的图像部分,一个用于颜色。
在 javascript 上,在将颜色画布的颜色和两个画布的宽度设置为 window.innerWidth 后,我得到的背景图像是:
imageObj.src = $('html').css('background-image').replace(/^url|[\(\)]/g, '');
现在问题来了。我想将裁剪后的图像绘制到图像画布上,这样我就可以应用乘法效果。我正在尝试执行以下操作:
imageObj.onload = function(){
// getting the background-image height
var imageHeight = window.innerWidth * imageObj.height / imageObj.width;
// get the corresponding pixels of the source image that correspond to the first 192 pixels of the background-image
var croppedHeight = 192 * imageObj.height / imageHeight;
// draw the image to the canvas
imageCanvas.drawImage(imageObj, 0, 0, imageObj.width, croppedHeight, 0, 0, window.innerWidth, 192);
// apply the multiply effect
colorCanvas.blendOnto( imageCanvas, 'multiply');
}
但是我做错了得到裁剪的高度。
例如:对于 1536x1152 图像和 1293x679 浏览器容器,我得到的源裁剪高度值为 230,但要获得正确的裁剪,我需要使用 296 左右的值。
编辑:
我在 css 上使用 background-size:cover 来创建背景图像
编辑2:
我创建了一个fiddle 来说明问题。如果您取消注释 //cHeight *= magicConstant; 行,裁剪后的图像看起来会好很多,但事情不再有意义。我删除了提琴手的乘法效果,但这并不是重现问题所必需的。我还注意到,如果我从 URL 中删除第二个画布,行为会发生变化。
顺便说一句,这种行为发生在 google chrome 上,但我认为同样的事情发生在 safari 和 firefox 上。
【问题讨论】:
-
你能在 jsfiddle.net 上创建一个例子吗?可能会帮助我们为您找到答案。此外,行为(获得 230 像素与 296 像素)在多个浏览器中是否一致?
-
@MarcGagne 我将示例添加到问题中
标签: javascript html canvas