色の錯視 左右の四角の色は同じ
縮小してみたり、画面をナナメから見るとより錯視が効くかもしれない
view source
JavaScript
document.title = '色の錯視 左右の四角の色は同じ';
//縮小してみたり、画面をナナメから見るとより錯視が効くかもしれない
//canvas-color-optical-illusions
let { canvas, ctx, cx, cy, w, h, min, demo } = readyCanvas();
function hslToRgb(h, s, l) {
s /= 100;
l /= 100;
let c = (1 - Math.abs(2 * l - 1)) * s;
let x = c * (1 - Math.abs((h / 60) % 2 - 1));
let m = l - c/2;
let r = 0, g = 0, b = 0;
if (0 <= h && h < 60) [r, g, b] = [c, x, 0];
else if (60 <= h && h < 120) [r, g, b] = [x, c, 0];
else if (120 <= h && h < 180) [r, g, b] = [0, c, x];
else if (180 <= h && h < 240) [r, g, b] = [0, x, c];
else if (240 <= h && h < 300) [r, g, b] = [x, 0, c];
else [r, g, b] = [c, 0, x];
return `rgb(${Math.round((r + m)*255)}, ${Math.round((g + m)*255)}, ${Math.round((b + m)*255)})`;
}
function draw(){
let width = w;
let height = h;
// Step 1: Random hue
const baseHue = Math.floor(Math.random() * 360);
const saturation = 80;
const lightness = 60;
// Step 2 & 3: Related colors
const colorA = hslToRgb(baseHue, saturation, lightness); // Random
const colorB = hslToRgb((baseHue + 90) % 360, saturation, lightness); // 90° shifted
const colorC = hslToRgb((baseHue + 270) % 360, saturation, lightness); // Opposite of B
// Step 4: Fill left and right backgrounds
ctx.fillStyle = colorC;
ctx.fillRect(0, 0, width / 2, height); // Left half
ctx.fillStyle = colorB;
ctx.fillRect(width / 2, 0, width / 2, height); // Right half
// Step 5: Draw center squares with colorA
const squareSize = min/4;
ctx.fillStyle = colorA;
ctx.fillRect((width / 4) - squareSize / 2, height / 2 - squareSize / 2, squareSize, squareSize); // Left
ctx.fillRect((3 * width / 4) - squareSize / 2, height / 2 - squareSize / 2, squareSize, squareSize); // Right
// Step 6: Overlay evenly spaced dots
const dotRadius = squareSize / 16; // 10px
const dotSpacing = dotRadius*2.4; // spacing between dot centers
function drawGridDots(startX, endX, color) {
ctx.fillStyle = color;
for (let y = dotSpacing / 2; y < height; y += dotSpacing) {
for (let x = startX + dotSpacing / 2; x < endX; x += dotSpacing) {
ctx.beginPath();
ctx.arc(x, y, dotRadius, 0, Math.PI * 2);
ctx.fill();
}
}
}
// Left dots with colorC, Right dots with colorB
drawGridDots(0, width / 2, colorB);
drawGridDots(width / 2, width, colorC);
ctx.fillStyle = colorA;
ctx.fillRect(0, 0, width, height/80);
}
draw();
canvas.addEventListener('click', draw);
window.addEventListener('resize', () => {
setTimeout(() => {
draw();
}, 1);
});
CSS
HTML
ページのソースを表示 : Ctrl+U , DevTools : F12
view-source:https://hi0a.com/game/canvas-color-optical-illusions/
ABOUT
hi0a.com 「ひまあそび」は無料で遊べるミニゲームや便利ツールを公開しています。
プログラミング言語の動作デモやWEBデザイン、ソースコード、フロントエンド等の開発者のための技術を公開しています。
必要な機能の関数をコピペ利用したり勉強に活用できます。
プログラムの動作サンプル結果は画面上部に出力表示されています。
環境:最新のブラウザ GoogleChrome / Windows / Android / iPhone 等の端末で動作確認しています。
画像素材や音素材は半分自作でフリー素材配布サイトも利用しています。LINK参照。
仕様変更、API廃止等、実験途中で動かないページもあります。