david2tdw / blog

学习记录
1 stars 1 forks source link

[canvas] canvas绘制网页背景图 #211

Open david2tdw opened 3 years ago

david2tdw commented 3 years ago
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>canvas background</title>
  </head>
  <body>
    <canvas id="canvas" width="200" height="200"></canvas>
  </body>
  <script>
    ;(function () {
      var canvas = document.getElementById('canvas'),
        ctx = canvas.getContext('2d')
      if (!canvas.getContext) {
        alert('你的浏览器不支持canvas!')
        return
      }
      canvas.width = 903
      canvas.height = 657

      var background = new Image()
      background.src =
        'https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/34130c52ddb047c89291aaba0bd02699~tplv-k3u1fbpfcp-watermark.image'

      // Make sure the image is loaded first otherwise nothing will draw.
      background.onload = function () {
        ctx.drawImage(background, 0, 0)
        ctx.fillStyle = 'red'
        ctx.beginPath()
        ctx.moveTo(75, 40)
        ctx.bezierCurveTo(75, 37, 70, 25, 50, 25)
        ctx.bezierCurveTo(20, 25, 20, 62.5, 20, 62.5)
        ctx.bezierCurveTo(20, 80, 40, 102, 75, 120)
        ctx.bezierCurveTo(110, 102, 130, 80, 130, 62.5)
        ctx.bezierCurveTo(130, 62.5, 130, 25, 100, 25)
        ctx.bezierCurveTo(85, 25, 75, 37, 75, 40)
        ctx.fill()
      }
    })()
  </script>
</html>

HTML5 Canvas background image

david2tdw commented 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>

HTMLCanvasElement.toDataURL()