快应用使用canvas替换背景色

canvas 的颜色支持各种 CSS 色彩值。

// 以下值均为 '红色'
ctx.fillStyle = 'red' //色彩名称
ctx.fillStyle = '#ff0000' //十六进制色值
ctx.fillStyle = 'rgb(255,0,0)' //rgb色值
ctx.fillStyle = 'rgba(255,0,0,1)' //rgba色值

一:

渐变色

除了使用纯色,还支持使用渐变色。先创建渐变色对象,并将渐变色对象作为样式进行绘图,就能绘制出渐变色的图形。

渐变色对象可以使用 createLinearGradient 创建线性渐变,然后使用 addColorStop 上色。

这里要注意的是,渐变色对象的坐标尺寸都是相对画布的。应用了渐变色的图形实际起到的是类似“蒙版”的效果。

//填充绘制一个矩形,填充颜色为深红到深蓝的线性渐变色
const linGrad1 = ctx.createLinearGradient(0, 0, 300, 300)
linGrad1.addColorStop(0, 'rgb(200, 0, 0)')
linGrad1.addColorStop(1, 'rgb(0, 0, 200)')
ctx.fillStyle = linGrad1
ctx.fillRect(20, 20, 200, 200)
<template>
  <div class="doc-page">
    <div class="content">
      <canvas class="new-canvas" id="new-canvas"></canvas>
      <image src="../Common/imgs/beauty.jpg" style="width: 500px; height: 600px;"></image>
    </div>
  </div>
</template>

<style>
.content {
  flex-direction: column;
  align-items: center;

} .new-canvas { width: 500px; height: 600px; background-color: blue; } </style> <script> export default { private: { drawComplete: false }, onInit() { this.$page.setTitleBar({ text: 'canvas简单绘制' }) }, onShow() { if (!this.drawComplete) { this.drawCanvas() } }, drawCanvas() { const canvas = this.$element('new-canvas') //获取 canvas 组件  const ctx = canvas.getContext('2d') //获取 canvas 绘图上下文  const img = new Image() //新建图像对象  img.src = '../Common/imgs/beauty.jpg' //加载本地图片 //加载成功的回调  img.onload = () => { // 将图片原封不动的绘制在画布上,是最基本的绘制方法  ctx.drawImage(img, 0, 0) console.log('图片加载完成') } //加载失败的回调  img.onerror = () => { console.log('图片加载失败') } this.drawComplete = true } } </script>

猜你喜欢

转载自www.cnblogs.com/DZzzz/p/12710771.html