滑鼠繪製的時候,取滑鼠目前區塊的顏色值,然後設定畫筆的顏色,但是,取色老是差別很大,不知道是不是我的計算有問題,求助!
#
<!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="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>
漂亮男人2017-06-08 11:05:00
取當前座標顏色的時候將寬高設為1PX呢?
var imgData = ctx.getImageData(pos.x, pos.y, 1, 1);
剛好我也在弄這塊,
https://github.com/S-mohan/ca...