javascript - 点击画布上的 Javascript 10 行告诉您点击了哪一行
问题描述
我必须在画布上用 10 种随机颜色绘制 10 条随机线。如果我单击一行,我会打印出该行的顺序和该行的颜色。如何解决这个问题?
E1:另一个问题是,我怎样才能在特定的 X、Y 坐标上获得画布颜色?
解决方案
要使用 10 个随机位置和颜色绘制线条,请使用Math.random();
,当然还有<canvas>
元素。
要获取光标位置,请使用element.clientX
和element.clientY
属性。
HTML:
<canvas id="_canvas"></canvas>
JavaScript 代码将完成所有工作,请阅读评论:
var element = document.getElementById('_canvas'); //Get the element
var ctx = element.getContext("2d"); //...And its context...
var cols = []; //Whoah! The array where the colors will be stored in.
let width = element.offsetWidth; //Get the width of the canvas,
let height = element.offsetHeight; //And the height!
for(i = 0; i < 10; i++) {
let r = Math.floor(Math.random() * 255); //Get a random color for the line, the red value,
let g = Math.floor(Math.random() * 255); //Green,
let b = Math.floor(Math.random() * 255); //And blue.
r = parseInt(r); //Remove decimal numbers.
g = parseInt(g);
b = parseInt(b);
var rgbToHex = function (rgb) { //And this function converts RGB to HEX!
var hex = Number(rgb).toString(16);
if (hex.length < 2) {
hex = "0" + hex;
}
return hex;
};
var fullColorHex = function(r,g,b) { //I mean this function converts RGB to HEX, but... anyway...
var red = rgbToHex(r);
var green = rgbToHex(g);
var blue = rgbToHex(b);
return red+green+blue;
};
let hexval = "#" + fullColorHex(r, g, b); //Now convert our RGB value to a hexadecimal number and add a "sharp" to the beginning of it!
ctx.beginPath(); //Alright now the serious stuff, begin painting.
ctx.moveTo(Math.random() * (+width - +0) + +0, Math.random() * (+height - +0) + +0); //From a random position,
ctx.lineTo(Math.random() * (+width - +0) + +0, Math.random() * (+height - +0) + +0); //To a random position!
ctx.strokeStyle = hexval; //change the line's color.
ctx.lineWidth = 8; //Change the strength of the lines, they will look insane but you will never click on them without this.
cols.push(hexval.replace("#", ""));
ctx.stroke(); //Draw it!
}
document.onclick = function(e) {
if(e.target == element) { //Does the user click on the canvas?
var x = e.clientX; //Get the mouse position
var y = e.clientY;
var c = element.getContext('2d');
var p = c.getImageData(x, y, 1, 1).data;
var hex = "#" + ("000000" + fullColorHex(p[0], p[1], p[2])).slice(-6); //Get the color of the pixel!
for(i = 0; i < 10; i++) {
console.log("Colors: " + cols[i] + ", hex: " + hex);
if("#" + cols[i] == hex) {
alert("Order: " + i + ", color: " + hex); //Done!
}
}
}
};
CodePen:https ://codepen.io/marchmello/pen/MWwMyog?editors=0010
推荐阅读
- vb.net - 如何搜索文件并将其附加到电子邮件
- r - 数据框行元素的成对比较
- powerbi - Dax 条件计算
- r - 为什么在 Shiny 中列不跨页面分布?
- ssis - SSIS 中与区域设置无关的 IsWeekEnd 表达式
- notepad++ - 在记事本++中的某一列之后删除字符串
- javascript - Graphql - 有没有办法同时插入两个表,但第二个表依赖于第一个表的返回?
- selenium - selenium 中是否有任何功能可以在使用 java 不可见的字段中输入文本?
- java - org.springframework.web.bind.MissingServletRequestParameterException:必需的字符串参数“文本”不存在
- python - 保存显示 Plotly Express 小部件的 Jupyter Notebook