javascript - 使用 javascript 在鼠标悬停时显示图像的灰度版本。在 Firefox 中可能吗?

标签 javascript html css firefox

<!DOCTYPE html>
<html>
 <head>
  <title> New Document </title>
<script type="text/javascript">
window.onload = function ()  {
  var area = document.getElementById('area');
  alert('area:'+area);   
  var context = area.getContext('2d');
  alert('context:'+context);
  if (context) {
    var imgd = context.getImageData(0, 0, 500, 300);
    var pix = imgd.data;
    for (var i = 0, n = pix.length; i < n; i += 4) {
      var grayscale = pix[i  ] * .3 + pix[i+1] * .59 + pix[i+2] * .11;
      pix[i]   = grayscale;   // red
      pix[i+1] = grayscale;   // green
      pix[i+2] = grayscale;   // blue
    }
    context.putImageData(imgd, 0, 0);
  }
};
</script>
 </head>
  <body>
   <canvas id="area" width="500" height="300">
     <img id="canvasSource" src="http://www.treehugger.com/elephant-national-heritage-animal-india.jpg" alt="Canvas Source" />
   </canvas>
</body>
</html>

最佳答案

您需要小写的 2d 并将脚本移动到 head 标签内

area.getContext('2d');

这里是一些可能工作得更好的代码:http://www.permadi.com/tutorial/jsCanvasGrayscale/index.html

这是我的测试 html - 我还没有看到图像

<!DOCTYPE html>
<html>
 <head>
  <title> New Document </title>
<script type="text/javascript">
window.onload = function ()  {
  var area = document.getElementById('area');
  alert('area:'+area);   
  var context = area.getContext('2d');
  alert('context:'+context)
  if (context) {
    var imgd = context.getImageData(0, 0, 500, 300);
    var pix = imgd.data;
    for (var i = 0, n = pix.length; i < n; i += 4) {
      var grayscale = pix[i  ] * .3 + pix[i+1] * .59 + pix[i+2] * .11;
      pix[i]   = grayscale;   // red
      pix[i+1] = grayscale;   // green
      pix[i+2] = grayscale;   // blue
    }
    context.putImageData(imgd, 0, 0);
  }
};
</script>
 </head>
  <body>
   <canvas id="area" width="500" height="300">
     <img id="canvasSource" src="http://www.treehugger.com/elephant-national-heritage-animal-india.jpg" alt="Canvas Source" />
   </canvas>
</body>
</html>

关于javascript - 使用 javascript 在鼠标悬停时显示图像的灰度版本。在 Firefox 中可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7200016/

相关文章:

javascript - 将javascript对象转换为有序的逗号分隔值

javascript - 如何在 javascript 中对超过 32 位的变量进行按位 AND 操作?

Javascript多图像颜色变化

html - 个人资料照片上的按钮

javascript - (节点:19502) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'indexOf' of undefined

php - 下拉菜单的动态变量onchange

javascript - 在 JavaScript 等式中使用 HTML 文本框中的数字

html - 从上层元素获取透明度

android - 如何防止 HTML 签名中的图像在 iphone 和 Android 上换行?

javascript - 仅在定义时分配属性