使用JavaScript或jQuery,如何在鼠标移动时获取RGB颜色< img>或者< div>分子 [英] Using JavaScript or jQuery, how can I get the RGB color where ever the mouse is moving specially in <img> or <div> elements

查看:283
本文介绍了使用JavaScript或jQuery,如何在鼠标移动时获取RGB颜色< img>或者< div>分子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张图片,< img src =/ meAndMy / face.jpg/> 。无论何时何地移动我的鼠标光标,我都试图获得RGB颜色。

I have an image, <img src="/meAndMy/face.jpg" />. I am trying to get the RGB color when ever or where ever I move my mouse cursor.

如何使用jQuery或纯JavaScript执行此操作?例如: http://www.script-tutorials.com/demos/158/index .html

How can I do this with jQuery or plain JavaScript? e.g: http://www.script-tutorials.com/demos/158/index.html

跟进(用于复制粘贴测试):

<?=$this->headScript(); ?>
<script>
$(document).ready(function()
{

   var image = new Image();
   var ctx = $('#panel')[0].getContext("2d");

   /* Load the picture empty.jpg */
   image.onload = function () 
   {
     ctx.drawImage(image, 0, 0, image.width, image.height);
   }
   /* How can i reload later new?
      image.empty; */
   image.src = "/agents/empty.jpg";

   /* On mouse over to my image, show me the background with RGB  
      change mousemove to click if requires */
   $('#panel').mousemove(function(e) 
   { 
    /* Leave as it is */
    var canvasOffset = $(this).offset();
    var canvasX = Math.floor(e.pageX - canvasOffset.left);
    var canvasY = Math.floor(e.pageY - canvasOffset.top);
    var imageData = ctx.getImageData(canvasX, canvasY, 1, 1);
    var pixel = imageData.data;    
    var pixelColor = "rgba("+pixel[0]+", "+pixel[1]+", "+pixel[2]+", "+pixel[3]+")";

    /* Meat */
    $(document.body).css('background-color',pixelColor);

   });

});

</script>

<body>
  <canvas id="panel" width="500" height="333"></canvas>
<body>


推荐答案

你可以像演示的脚本那样做确实。请注意,该演示不使用img元素,而是将图像加载到canvas元素中。 canvas API允许您像这样获取像素数据:

You can do it just like the script for that demo does. Note that the demo does not use an img element, rather it loads the image into a canvas element. The canvas API allows you to get the pixel data like so:

var imageData = ctx.getImageData(canvasX, canvasY, 1, 1);
var pixel = imageData.data;

参见 HTML 5 canvas API 了解详情。

如果出于何种原因你需要将图像加载到img元素中,而不是画布元素,你可以:

If for whatever reason you are required to load the image into the img element, as opposed to a canvas element, you could:


  1. 动态创建一个canvas元素与img相同的大小和位置。

  2. 通过画布上下文中的drawImage方法将图像数据从img复制到画布。

  3. 隐藏img元素,将画布留在原位。

这篇关于使用JavaScript或jQuery,如何在鼠标移动时获取RGB颜色&lt; img&gt;或者&lt; div&gt;分子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆