我正在使用 context-blender对具有固定颜色的 html 背景图像的前 192 像素应用乘法效果,以实现页面标题的透明效果。
在 html 上我有 2 个 Canvas 。一个用于应用乘法效果的图像部分,一个用于颜色。
在 javascript 上,将颜色 Canvas 的颜色和两个 Canvas 的宽度设置为 window.innerWidth 后,我得到背景图像:
imageObj.src = $('html').css('background-image').replace(/^url|[\(\)]/g, '');
问题来了。我想将裁剪后的图像绘制到图像 Canvas 上,这样我就可以应用乘法效果。我正在尝试执行以下操作:
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;
行,裁剪后的图像看起来好多了,但事情就不再有意义了。我删除了对 fiddler 的乘法效果,但这并不是重现问题所必需的。我还注意到,如果我从 URL 中删除第二个 Canvas ,行为会发生变化。
顺便说一句,这种行为发生在 google chrome 上,但我认为同样的事情发生在 safari 和 firefox 上。
最佳答案
好的,我已经解决了。男人太难了!主要是因为你忘了设置 imageCanvas 的 Canvas 高度。图像有白色边框也无济于事。我花了很多时间试图找出填充的来源。
所以开始吧,对于 fiddle 的情况,在函数doBlending()
中,设置imageCanvas.canvas.height = height;
那么 crop()
中的计算需要涵盖 2 种可能性。图像是按高度缩放并在左侧 chop ,还是按宽度缩放并在底部 chop ?我不会为你写这两个,但这是针对高度缩放的情况:
function crop(imageObj, imageCanvas, colorCanvas) {
// Assumes bg image is scaled for hight
var scale = imageObj.height / window.innerHeight;
var targetHeight = imageCanvas.canvas.height;
var targetWidth = window.innerWidth;
imageCanvas.drawImage(imageObj,
0, 0, targetWidth * scale, targetHeight * scale,
0, 0, targetWidth, targetHeight);
}
我真的不知道您在示例中是从哪里得出比例因子的。图像将通过将 x 和 y 维度乘以某个比例因子来缩放。这就是保持纵横比的方式。比例因子将是使图像的高度与窗口的高度匹配的那个和使图像的宽度与窗口的宽度匹配的那个中的较大者。
关于javascript - html5图像裁剪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10121011/