Rumah > Artikel > hujung hadapan web > 如何用js获取当前页面已加载的图片的binary?
譬如说一个网页是这样的:
<code class="language-js"><span class="kd">function</span> <span class="nx">getBase64Image</span><span class="p">(</span><span class="nx">img</span><span class="p">)</span> <span class="p">{</span>
<span class="kd">var</span> <span class="nx">canvas</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">createElement</span><span class="p">(</span><span class="s2">"canvas"</span><span class="p">);</span>
<span class="nx">canvas</span><span class="p">.</span><span class="nx">width</span> <span class="o">=</span> <span class="nx">img</span><span class="p">.</span><span class="nx">width</span><span class="p">;</span>
<span class="nx">canvas</span><span class="p">.</span><span class="nx">height</span> <span class="o">=</span> <span class="nx">img</span><span class="p">.</span><span class="nx">height</span><span class="p">;</span>
<span class="kd">var</span> <span class="nx">ctx</span> <span class="o">=</span> <span class="nx">canvas</span><span class="p">.</span><span class="nx">getContext</span><span class="p">(</span><span class="s2">"2d"</span><span class="p">);</span>
<span class="nx">ctx</span><span class="p">.</span><span class="nx">drawImage</span><span class="p">(</span><span class="nx">img</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">);</span>
<span class="kd">var</span> <span class="nx">dataURL</span> <span class="o">=</span> <span class="nx">canvas</span><span class="p">.</span><span class="nx">toDataURL</span><span class="p">(</span><span class="s2">"image/png"</span><span class="p">);</span>
<span class="k">return</span> <span class="nx">dataURL</span><span class="p">.</span><span class="nx">replace</span><span class="p">(</span><span class="sr">/^data:image\/(png|jpg);base64,/</span><span class="p">,</span> <span class="s2">""</span><span class="p">);</span>
<span class="p">}</span>
</code>
document.querySelectorAll('img')
大概类似于document.getELementById('cool').onload=function(){//具体操作};