源代码:
<html> <div style="width:200px;height:200px;"id="cloud">test canvas</div> <canvas style="display:none;"id="can"width="200"height="200"></canvas> <script>(function() { var canvas = document.getElementById('can'), context; if(!canvas.getContext) { alert('你的浏览器不支持 canvas!'); return; } context = canvas.getContext('2d'); context.fillStyle = 'red'; context.beginPath(); context.moveTo(75,40); context.bezierCurveTo(75,37,70,25,50,25); context.bezierCurveTo(20,25,20,62.5,20,62.5); context.bezierCurveTo(20,80,40,102,75,120); context.bezierCurveTo(110,102,130,80,130,62.5); context.bezierCurveTo(130,62.5,130,25,100,25); context.bezierCurveTo(85,25,75,37,75,40); context.fill(); var url = context.canvas.toDataURL(); document.getElementById('cloud').style.backgroundImage = 'url("' + url + '")'; })(); </script> </html>
效果如下:
实现原理: