I'm using a colorwheel picker from this website, and I came up with a problem. When I add text above the color wheel, then scroll down and change the colorwheels color, the colorwheels cursor isn't contained in the actual circle. (It makes an imaginary circle in another place, and the colorwheels cursor is constrained in that imaginary circle.)
Another issue, which might be related to the first one is that if you zoom up in the browser, (in chrome: ctrl +) the colorwheels cursor stays position like a fixed element, it follows the scrolling.
How can I get the colorwheels cursor to always stay in the circle?
Relevant code (Line 210 - 211 in JSFiddle):
hsv_mapCursor.style.left = ((x * r + colorDiscRadius + doc.body.scrollLeft + doc.documentElement.scrollLeft) - 1) + 'px';
hsv_mapCursor.style.top = ((y * r + colorDiscRadius + doc.body.scrollTop + doc.documentElement.scrollTop) - 1) + 'px';
JSFiddle
var Tools = {}, // provides functions like addEvent, ... getOrigin, etc.
startPoint,
currentTarget,
currentTargetHeight = 0;
/* ----------------------------------- */
/* --------- Tool Functions ---------- */
/* ----------------------------------- */
function getOrigin(elm) {
var box = (elm.getBoundingClientRect) ? elm.getBoundingClientRect() : {
top: 0,
left: 0
},
doc = elm && elm.ownerDocument,
body = doc.body,
win = doc.defaultView || doc.parentWindow || window,
docElem = doc.documentElement || body.parentNode,
clientTop = docElem.clientTop || body.clientTop || 0, // border on html or body or both
clientLeft = docElem.clientLeft || body.clientLeft || 0;
return {
left: box.left + (win.pageXOffset || docElem.scrollLeft) - clientLeft,
top: box.top + (win.pageYOffset || docElem.scrollTop) - clientTop
};
}
function addEvent(obj, type, func) {
addEvent.cache = addEvent.cache || {
_get: function(obj, type, func, checkOnly) {
var cache = addEvent.cache[type] || [];
for (var n = cache.length; n--;) {
if (obj === cache[n].obj && '' + func === '' + cache[n].func) {
func = cache[n].func;
if (!checkOnly) {
cache[n] = cache[n].obj = cache[n].func = null;
cache.splice(n, 1);
}
return func;
}
}
},
_set: function(obj, type, func) {
var cache = addEvent.cache[type] = addEvent.cache[type] || [];
if (addEvent.cache._get(obj, type, func, true)) {
return true;
} else {
cache.push({
func: func,
obj: obj
});
}
}
};
if (!func.name && addEvent.cache._set(obj, type, func) || typeof func !== 'function') {
return;
}
if (obj.addEventListener) obj.addEventListener(type, func, false);
else obj.attachEvent('on' + type, func);
}
function removeEvent(obj, type, func) {
if (typeof func !== 'function') return;
if (!func.name) {
func = addEvent.cache._get(obj, type, func) || func;
}
if (obj.removeEventListener) obj.removeEventListener(type, func, false);
else obj.detachEvent('on' + type, func);
}
Tools.getOrigin = getOrigin;
Tools.addEvent = addEvent;
Tools.removeEvent = removeEvent;
/* ---------------------------------- */
/* ---- HSV-circle color picker ----- */
/* ---------------------------------- */
// Create HSV-circle Relavent Variables
var hsv_map = document.getElementById('hsv_map'),
colorDiskWrapper = document.getElementById('colorDiskWrapper'),
colorDisc = document.getElementById('surface'),
hsv_mapCover = document.getElementById('cover'),
hsv_mapCursor = document.getElementById('hsv-cursor'),
luminenceBarWrapper = document.getElementById('luminenceBarWrapper'),
hsv_barBGLayer = document.getElementById('bar-bg'),
hsv_barWhiteLayer = document.getElementById('bar-white'),
luminanceBar = document.getElementById('luminanceBar'),
hsv_barcursor = document.getElementById('hsv-barcursor'),
hsv_barCursors = document.getElementById('hsv-barcursors'),
hsv_barCursorsCln = hsv_barCursors.className,
luminanceBarContext = luminanceBar.getContext("2d"),
colorDiscHeight = colorDisc.offsetHeight,
colorDiscRadius = colorDisc.offsetHeight / 2;
// generic function for drawing a canvas disc
var drawDisk = function(ctx, coords, radius, steps, colorCallback) {
var x = coords[0] || coords, // coordinate on x-axis
y = coords[1] || coords, // coordinate on y-axis
a = radius[0] || radius, // radius on x-axis
b = radius[1] || radius, // radius on y-axis
angle = 360,
rotate = 0,
coef = Math.PI / 180;
ctx.save();
ctx.translate(x - a, y - b);
ctx.scale(a, b);
steps = (angle / steps) || 360;
for (; angle > 0; angle -= steps) {
ctx.beginPath();
if (steps !== 360) ctx.moveTo(1, 1); // stroke
ctx.arc(1, 1, 1, (angle - (steps / 2) - 1) * coef, (angle + (steps / 2) + 1) * coef);
if (colorCallback) {
colorCallback(ctx, angle);
} else {
ctx.fillStyle = 'black';
ctx.fill();
}
}
ctx.restore();
},
drawCircle = function(ctx, coords, radius, color, width) { // uses drawDisk
width = width || 1;
radius = [
(radius[0] || radius) - width / 2, (radius[1] || radius) - width / 2
];
drawDisk(ctx, coords, radius, 1, function(ctx, angle) {
ctx.restore();
ctx.lineWidth = width;
ctx.strokeStyle = color || '#000';
ctx.stroke();
});
};
if (colorDisc.getContext) {
drawDisk( // HSV color wheel with white center
colorDisc.getContext("2d"), [colorDisc.width / 2, colorDisc.height / 2], [colorDisc.width / 2 - 1, colorDisc.height / 2 - 1],
360,
function(ctx, angle) {
var gradient = ctx.createRadialGradient(1, 1, 1, 1, 1, 0);
gradient.addColorStop(0, 'hsl(' + (360 - angle + 0) + ', 100%, 50%)');
gradient.addColorStop(1, "#FFFFFF");
ctx.fillStyle = gradient;
ctx.fill();
}
);
drawCircle( // gray border
colorDisc.getContext("2d"), [colorDisc.width / 2, colorDisc.height / 2], [colorDisc.width / 2, colorDisc.height / 2],
'#555',
3
);
}
// draw the luminanceBar bar
var gradient = luminanceBarContext.createLinearGradient(0, 0, 0, colorDiscHeight);
gradient.addColorStop(0, "transparent");
gradient.addColorStop(1, "black");
luminanceBarContext.fillStyle = gradient;
luminanceBarContext.fillRect(0, 0, luminanceBar.offsetWidth, colorDiscHeight);
// Manage Color Wheel Mouse Events
var renderHSVPicker = function(color) { // used in renderCallback of 'new ColorPicker'
var pi2 = Math.PI * 2,
x = Math.cos(pi2 - color.hsv.h * pi2),
y = Math.sin(pi2 - color.hsv.h * pi2),
r = color.hsv.s * colorDiscRadius;
hsv_mapCover.style.opacity = 1 - color.hsv.v;
// this is the faster version...
hsv_barWhiteLayer.style.opacity = 1 - color.hsv.s;
hsv_barBGLayer.style.backgroundColor = 'rgb(' +
color.hueRGB.r + ',' +
color.hueRGB.g + ',' +
color.hueRGB.b + ')';
var doc = window.document;
hsv_mapCursor.style.left = ((x * r + colorDiscRadius + doc.body.scrollLeft + doc.documentElement.scrollLeft) - 1) + 'px';
hsv_mapCursor.style.top = ((y * r + colorDiscRadius + doc.body.scrollTop + doc.documentElement.scrollTop) - 1) + 'px';
hsv_mapCursor.style.borderColor = hsv_barcursor.style.borderColor = color.RGBLuminance > 0.22 ? 'black' : 'white';
hsv_barcursor.style.top = (((1 - color.hsv.v) * colorDiscRadius * 2 + doc.body.scrollTop + doc.documentElement.scrollTop) + -7) + 'px';
};
var myColor = new Colors(),
doRender = function(color) {
renderHSVPicker(color);
},
renderTimer,
// those functions are in case there is no ColorPicker but only Colors involved
startRender = function(oneTime) {
if (oneTime) { // only Colors is instanciated
doRender(myColor.colors);
} else {
renderTimer = window.setInterval(
function() {
doRender(myColor.colors);
// http://stackoverflow.com/questions/2940054/
}, 13); // 1000 / 60); // ~16.666 -> 60Hz or 60fps
}
},
stopRender = function() {
window.clearInterval(renderTimer);
};
// Create Event Functions
var hsvDown = function(e) { // mouseDown callback
var target = e.target || e.srcElement;
if (e.preventDefault) e.preventDefault();
//currentTarget = target.id ? target : target.parentNode;
if (target === hsv_mapCover || target === hsv_mapCursor || target === hsv_barcursor) {
currentTarget = target.parentNode;
} else if (target === hsv_barCursors) {
currentTarget = target;
} else {
return;
}
startPoint = Tools.getOrigin(currentTarget);
currentTargetHeight = currentTarget.offsetHeight; // as diameter of circle
Tools.addEvent(window, 'mousemove', hsvMove);
hsv_mapCover.style.cursor = hsv_mapCursor.style.cursor = 'none';
hsvMove(e);
startRender();
},
hsvMove = function(e) { // mouseMove callback
var r, x, y, h, s;
if (currentTarget === colorDiskWrapper) { // the circle
r = currentTargetHeight / 2;
x = e.clientX - startPoint.left - r;
y = e.clientY - startPoint.top - r;
h = 360 - ((Math.atan2(y, x) * 180 / Math.PI) + (y < 0 ? 360 : 0));
s = (Math.sqrt((x * x) + (y * y)) / r) * 100;
myColor.setColor({
h: h,
s: s
}, 'hsv');
} else if (currentTarget === hsv_barCursors) { // the luminanceBar
myColor.setColor({
v: (currentTargetHeight - (e.clientY - startPoint.top)) / currentTargetHeight * 100
}, 'hsv');
}
};
// Initial Rendering
doRender(myColor.colors);
// Adde Events To Objects
Tools.addEvent(hsv_map, 'mousedown', hsvDown); // event delegation
Tools.addEvent(window, 'mouseup', function() {
Tools.removeEvent(window, 'mousemove', hsvMove);
hsv_mapCover.style.cursor = hsv_mapCursor.style.cursor = hsv_barCursors.style.cursor = 'pointer';
stopRender();
});
#wrapper {
width: 500px;
height: 500px;
background-color: pink;
}
#hsv_map {
width: 540px;
height: 500px;
position: absolute;
}
#colorDiskWrapper {
border-radius: 50%;
position: relative;
width: 500px;
}
#cover {
background-color: black;
border-radius: 50%;
cursor: pointer;
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
}
#bar-bg,
#bar-white {
position: absolute;
right: 0;
top: 0;
width: 15px;
height: 500px;
}
#bar-white {
background-color: #fff;
}
#hsv-cursor {
position: absolute;
border: 2px solid #eee;
border-radius: 50%;
width: 9px;
height: 9px;
margin: -5px;
cursor: pointer;
}
.no-cursor #hsv-cursor,
#hsv_map.no-cursor #cover {
cursor: none;
/* also works in IE8 */
/*url(_blank.gif), url(_blank.png), url(_blank.cur), auto;*/
}
#luminanceBar {
position: absolute;
right: 0;
top: 0;
}
#hsv-barcursors {
position: absolute;
right: -7.5px;
width: 30px;
top: 0;
height: 500px;
overflow: hidden;
cursor: pointer;
}
#hsv-barcursor {
position: absolute;
right: 7.5px;
width: 11px;
height: 11px;
border-radius: 50%;
border: 2px solid black;
margin-bottom: 5px;
}
<script src="https://rawgit.com/PitPik/colorPicker/master/colors.js"></script>
Lorem ipsum dolor sit amet, his id nonumy quaestio efficiantur. Quidam deleniti eum no, pri adhuc putant ea. Nec cu melius accusata, et vim lorem quaeque minimum. At aperiri principes complectitur eam, quo ne soleat accusamus ullamcorper, sed fugit adipiscing
no. Eripuit consequuntur quo no, his accusamus persequeris ea. Exerci delenit ad eos, ei sea tamquam ancillae necessitatibus. Est legere possim mnesarchum an. Vim nonumes expetendis ea, mei te mutat propriae platonem, per ut feugiat reprimique. Has deserunt
nominati liberavisse ut. Per cibo ubique omittam in, has te decore denique, justo nominavi id pro. Ei ius paulo deserunt pertinacia. Nec nostro expetenda id. Nec no esse interesset, id qui ferri errem. Qui possim ponderum platonem ea, nostro epicuri nam
in. Ei consul ubique conclusionemque eum, et alterum apeirian nam. Quem odio adipiscing has ei. Et has solum perfecto tincidunt, quo no indoctum prodesset. Pri ut tritani ceteros tractatos, in legere disputationi mea. Ne mel mutat graeci, mei eu doctus
appetere. Ius dicam imperdiet id, duo commune phaedrum ut, ut reque minim vis. Instructior signiferumque mea id. Nam ut vocibus recusabo consulatu. No mea postea mandamus prodesset, his hinc iusto in, no atqui consequat his. Discere sapientem id vel,
eam ea idque lucilius, ne eos labitur pericula. Ea dicat sonet nec, te pri libris putant eirmod, ancillae voluptatibus ut eam. Dicat commune necessitatibus nec cu, an enim purto menandri vel, eu ferri altera admodum duo.Lorem ipsum dolor sit amet, his
id nonumy quaestio efficiantur. Quidam deleniti eum no, pri adhuc putant ea. Nec cu melius accusata, et vim lorem quaeque minimum. At aperiri principes complectitur eam, quo ne soleat accusamus ullamcorper, sed fugit adipiscing no. Eripuit consequuntur
quo no, his accusamus persequeris ea. Exerci delenit ad eos, ei sea tamquam ancillae necessitatibus. Est legere possim mnesarchum an. Vim nonumes expetendis ea, mei te mutat propriae platonem, per ut feugiat reprimique. Has deserunt nominati liberavisse
ut. Per cibo ubique omittam in, has te decore denique, justo nominavi id pro. Ei ius paulo deserunt pertinacia. Nec nostro expetenda id. Nec no esse interesset, id qui ferri errem. Qui possim ponderum platonem ea, nostro epicuri nam in. Ei consul ubique
conclusionemque eum, et alterum apeirian nam. Quem odio adipiscing has ei. Et has solum perfecto tincidunt, quo no indoctum prodesset. Pri ut tritani ceteros tractatos, in legere disputationi mea. Ne mel mutat graeci, mei eu doctus appetere. Ius dicam
imperdiet id, duo commune phaedrum ut, ut reque minim vis. Instructior signiferumque mea id. Nam ut vocibus recusabo consulatu. No mea postea mandamus prodesset, his hinc iusto in, no atqui consequat his. Discere sapientem id vel, eam ea idque lucilius,
ne eos labitur pericula. Ea dicat sonet nec, te pri libris putant eirmod, ancillae voluptatibus ut eam. Dicat commune necessitatibus nec cu, an enim purto menandri vel, eu ferri altera admodum duo.
<div id="wrapper">
<div id="hsv_map">
<div id="colorDiskWrapper">
<canvas id="surface" width="500" height="500"></canvas>
<div id="cover"></div>
<div id="hsv-cursor"></div>
</div>
<div id="luminenceBarWrapper">
<div id="bar-bg"></div>
<div id="bar-white"></div>
<canvas id="luminanceBar" width="15" height="500"></canvas>
<div id="hsv-barcursors" id="hsv_cursors">
<div id="hsv-barcursor"></div>
</div>
</div>
</div>
</div>
add this to your css :
html, body {
width: 100%;
height: 100%;
overflow-x: hidden;
position: relative;
}
JSFIDDLE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With