const warp = document.getElementById('mainPic');
// 初始化主canvas
const obj = document.getElementById('canvas');
const ctx = obj.getContext('2d');
// 原始图片
const pic = new Image();
pic.src = "pic.jpg";
// 加载图片
pic.onload = function () {
ctx.drawImage(this, 0, 0, this.width, this.height);
// 获取图片像素信息
let imageData = ctx.getImageData(0,0,obj.width,obj.height);
let pixels = imageData.data;
//遍历像素点
for (let i=0; i<pixels.length; i+=4){
let r = pixels[i];
let g = pixels[i+1];
let b = pixels[i+2];
originImageData[i] = r;
originImageData[i+1] = g;
originImageData[i+2] = b;
//获取灰色
let gray = parseInt((r+g+b)/3);
pixels[i] = gray;
pixels[i+1] = gray;
pixels[i+2] = gray;
}
ctx.putImageData(imageData, 0,0);
// 点击事件
obj.addEventListener('click', function(event) {
let rect = obj.getBoundingClientRect();
let cx = event.clientX - rect.left * (obj.width / rect.width);
let cy = event.clientY - rect.top * (obj.height / rect.height);
console.log(cx,cy);
});
}
网友评论