Open david2tdw opened 3 years ago
关键点:canvas.toDataURL() style="display: none" 用来隐藏生成的canvas图案,通过canvas.toDataURL()将生成的图案赋值给html element元素的backgroundImage属性上。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div style="width: 200px; height: 200px; border: 1px solid green" id="cloud">
红心是我的背景图!红心是我的背景图!红心是我的背景图!红心是我的背景图!红心是我的背景图!红心是我的背景图!
</div>
<canvas style="display: none" id="can" width="300" height="300"></canvas>
</body>
<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()
document.getElementById('cloud').style.backgroundImage = 'url("' + canvas.toDataURL() + '")'
})()
</script>
</html>
HTML5 Canvas background image