图片部分区域颜色是否近似实例页面
回到相关文章 »效果:
//zxx: 点击图片可以切换素材
代码:
CSS代码:
.container img { display: block; width: 300px; height: 400px; user-select: none; } .container { width: 300px; position: relative; } .cover { position: absolute; left: 20px; right: 20px; top: 0; height: 100px; border: 2px solid yellow; cursor: move; }
HTML代码:
<div class="container"> <i id="cover" class="cover"></i> <img id="img" src="01.jpg"> </div> <p id="result"></p>
JS代码:
<script src="color-thief.js"></script> <script src="./image-similarity.js"></script> <script> let getSimilarity = function () { // 剪裁范围 // 注意,需要相对于原始图片尺寸 // 这里图片1/2缩放显示,因此需要乘以2 let bounding = [20, parseFloat(getComputedStyle(cover).top) + 2, 300 - 40, 100].map(v => v * 2); // 获得此时的范围颜色相似度 imageSimilarity(img.src, bounding).then(similarity => { // 0 极度相似 // 1 相似 // 2 不太相似 // 3 不相似 // 4 差异较大 if (similarity === 0) { result.innerHTML = '视觉色彩极度相似'; } else if (similarity === 1) { result.innerHTML = '视觉色彩相似'; } else if (similarity === 2) { result.innerHTML = '视觉色彩不太相似'; } else if (similarity === 3) { result.innerHTML = '视觉色彩不相似'; } else { result.innerHTML = '视觉色彩差异较大'; } }); }; let store = {}; cover.addEventListener('mousedown', (event) => { store.y = event.pageY; store.isMoving = true; store.top = parseFloat(getComputedStyle(cover).top) || 0; }); document.addEventListener('mousemove', event => { if (store.isMoving) { event.preventDefault(); let distanceY = event.pageY - store.y; let top = store.top + distanceY; if (top < 0) { top = 0; } else if (top + cover.offsetHeight > cover.parentElement.clientHeight) { top = cover.parentElement.clientHeight - cover.offsetHeight; } cover.style.top = top + 'px'; } }); document.addEventListener('mouseup', function () { if (store.isMoving) { store.isMoving = false; getSimilarity(); } }); // 默认进来先判断一次相似度 getSimilarity(); img.onclick = function () { this.src = /01/.test(this.src) ? '02.jpg' : '01.jpg'; getSimilarity(); }; </script>