gpt4 book ai didi

javascript - 读取 Canvas 像素的 RGB 值

转载 作者:太空狗 更新时间:2023-10-29 14:54:16 25 4
gpt4 key购买 nike

我在 Canvas 上放了一张图片,我想在用户将鼠标移到图片上时获取该图片像素的 RGB 值。这是我写的代码:

<canvas id="myCanvas" width="200" height="200" style="border: red;border-style: dotted">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");

var destX = 0;
var destY = 0;

var imageObj = new Image();
imageObj.onload = function()
{
context.drawImage(imageObj, destX, destY);
};
imageObj.src = "zain.jpg";

canvas.onclick = function(e) {
var x = e.pageX;
var y = e.pageY;
var canvasColor = context.getImageData(x, y, 1,1); // rgba e [0,255]
var pixels = canvasColor.data;
var r = pixels[0];
var g = pixels[1];
var b = pixels[2];
document.body.style.backgroundColor = "rgb("+r+','+g+','+b+")";
}

最佳答案

尝试一下:

var color = document.getElementById("color");
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");

var imageObj = new Image();
imageObj.onload = function(){
context.drawImage(imageObj, destX, destY);
};
imageObj.src = "zain.jpg";

canvas.onmousemove = function(e) {
// not so sure about these... might need to offset them or so
var x = e.x;
var y = e.y;

// set color now
var canvasColor = context.getImageData(x, y, 1, 1).data; // rgba e [0,255]
var r = canvasColor[0];
var g = canvasColor[1];
var b = canvasColor[2];

color.style.backgroundColor = 'rgb(' + r + ',' + g + ',' + b + ')';
}

请注意,该代码片段期望您在某处有一个 ID 为“color”的 div。它在那里设置像素颜色。

关于javascript - 读取 Canvas 像素的 RGB 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7373851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com