canvas-颜色选择器 原

2019-04-04 09:42:01 浏览数 (1)

实现目标:在画布上嵌入一个图片,鼠标在图像上移动的时候显示鼠标所在位置颜色信息

实现方法:

(1)创建一个图片对象

(2)图片对象加载完成时,执行获取颜色信息的函数

(3)颜色信息的函数主要包括,获取鼠标所在点的位置,通过getImageData获取鼠标所在点的像素对象,并最终获得rgba信息

(4)为canvas注册 mousemove 事件

代码语言:javascript复制
<body >
<canvas id="canvas" width="647" height="520" style=""></canvas>
<div id="color">鼠标浮到图片上移动显示选择的颜色</div>
<script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
  var img = new Image();
  img.src = 'images/rhino.jpg';
  var canvas = document.getElementById("canvas");
  var ctx = canvas.getContext("2d");
  img.onload = function() {
    ctx.drawImage(img,0,0);
	img.style.display="none"
  };
  var color = document.getElementById("color");
  function pick(event) {
    var x = event.layerX;
	var y = event.layerY;
	var pixel = ctx.getImageData(x,y,1,1);
	var data = pixel.data;
	var rgba = 'rgba(' data[0] ',' data[1] ',' data[2] ',' data[3]/255 ')';
	color.style.background = rgba;
	color.style.color = "#fff";
	color.innerText = rgba
  }
  canvas.addEventListener("mousemove",pick)

</script>
</body>

查看选择器效果

注意:

(1)图片的路径不能跨域,否则getImageData不执行,会报错显示Uncaught DOMException: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.

(2)要发布后才能正常显示

(adsbygoogle = window.adsbygoogle || []).push({});

0 人点赞