img元素crossOrigin属性跨域数据获取演示页面
展示
设置了crossorigin=""
没有设置crossorigin=""
代码
-
HTML:
<section> <h4>设置了crossorigin=""</h4> <img src="https://avatars3.githubusercontent.com/u/496048?s=120&v=4" crossorigin=""> <p> <button class="button">getImageData运行</button> </p> <div> <output></output> </div> </section> <section> <h4>没有设置crossorigin=""</h4> <img src="https://avatars3.githubusercontent.com/u/496048?s=120&v=4"> <p> <button class="button">getImageData运行</button> </p> <div> <output></output> </div> </section>
-
JS:
document.querySelectorAll('button').forEach(function (button) { button.addEventListener('click', function () { // 转换对象元素和输出结果元素 const eleImg = this.closest('section').querySelector('img'); const eleOutput = this.closest('section').querySelector('output'); // 创建画布元素 const canvas = document.createElement('canvas'); // 确定尺寸 canvas.width = eleImg.naturalWidth; canvas.height = eleImg.naturalHeight; // 绘制 const context = canvas.getContext('2d'); context.drawImage(eleImg, 0, 0); try { console.log(context.getImageData(0, 0, canvas.width, canvas.height)); eleOutput.className = 'success'; eleOutput.innerHTML = '获取成功,数据见控制台console输出'; } catch (err) { eleOutput.className = 'error'; eleOutput.innerHTML = '获取失败:' + err; } // 按钮禁用 button.disabled = true; }) });