您的位置:首页技术文章
文章详情页

javascript - 求助canvas绘制马赛克的问题,老是取色不准

浏览:31日期:2022-11-23 17:56:07

问题描述

鼠标绘制的时候,取鼠标当前区块的颜色值,然后设置画笔的颜色,但是,取色老是差别很大,不知道是不是我的计算有问题,求助!

javascript - 求助canvas绘制马赛克的问题,老是取色不准

<!DOCTYPE html><html><meta http-equiv='Content-Type' content='text/html; charset=utf-8' /><meta name='viewport' content='width=device-width,user-scalable=no,initial-scale=1,maximum-scale=1' /><title></title><head> <style>*{ margin: 0; padding: 0;}.box { position: fixed; top: 300px;}img { vertical-align: middle;} </style></head><body> <p class='box'><button id='create'>生成</button><button id='clear'>清除</button> </p> <canvas id='canvas'></canvas> <script src='https://www.haobala.com/wenda/js/jquery-1.9.1.js'></script> <script>// 本地图片路径var imgSrc = ’img/aaa.png’;var height = 300;var width = 480;//将图片分成100份var xW = width / 100;var yH = height / 100;var clip = new mosaic(height, width, imgSrc);function mosaic(height, width, src) { var img = new Image(); var canvas = $(’#canvas’)[0]; var ctx = canvas.getContext(’2d’);img.addEventListener(’load’, function (e) {var mousedown = false, offsetX = canvas.offsetLeft, offsetY = canvas.offsetTop;canvas.width = width;canvas.height = height;ctx.drawImage(img, 0, 0, width, height, 0, 0, width, height);$(’#clear’).on(’click’, function () { ctx.drawImage(img, 0, 0, width, height, 0, 0, width, height);});$(’#create’).on(’click’, function () { var images = new Image(); images.onload = function () {$(’body’).append(images); } images.src = canvas.toDataURL()});// 计算当前鼠标坐标值在这个100份格子中的位置function getPos(x, y){ var px, py; var result = {x, y}; var posArr = createPosArr(); for(var i = 0; i < posArr.length; i++){px = posArr[i].x;py = posArr[i].y;if(x >= px){ result.x = posArr[i].x; continue;} } for(var i = 0; i < posArr.length; i++){px = posArr[i].x;py = posArr[i].y;if(y >= py){ result.y = posArr[i].y; continue;} } return result;}function createPosArr(){ var arr = []; for(var i = 0; i < 100; i++){arr.push({ x: i * xW, y: i * yH}); } return arr;}function down(e) { e.preventDefault(); mousedown = true;}function up(e) { e.preventDefault(); mousedown = false;}function move(e) { if(!mousedown){return;} e.preventDefault();// 如果鼠标按下 if (mousedown) {var pos = getPos(e.clientX, e.clientY);console.log(pos);var imgData = ctx.getImageData(pos.x, pos.y, 5, 5);var red = imgData.data[0];var green = imgData.data[1];var blue = imgData.data[2];var alpha = imgData.data[3] / 255;ctx.fillStyle = ’rgba(’ + red + ’,’ + green + ’,’ + blue + ’,’ + alpha / 2 + ’)’ctx.fillRect(pos.x, pos.y, 10, 10); }}// 在源图像外显示目标图像。只有源图像外的目标图像部分会被显示,源图像是透明的。// ctx.globalCompositeOperation = ’destination-out’;canvas.addEventListener(’mousedown’, down);canvas.addEventListener(’mousemove’, move);canvas.addEventListener(’mouseup’, up); }); img.src = src;} </script></body></html>

问题解答

回答1:

可以试一下计算方格内的颜色平均值。去平均值,可以参考下:https://github.com/JackGit/ca...

回答2:

取当前坐标颜色的时候将宽高设为1PX呢?var imgData = ctx.getImageData(pos.x, pos.y, 1, 1);刚好我也在弄这块,https://github.com/S-mohan/ca...

标签: JavaScript