canvas 组件是系统里面本来就有的 可以直接拿过来使用
可以给他设置宽高 这里的宽高是一定要设置的 否则的话他会有默认宽300 和高150 的占位但是内容不会显示的(如下左图)
但是如果设置了背景图片内容还是会显示的 (如下右图)
然后这个标签就跟其他标签是一样的 可以写 style 和 class 来控制样式
height 和 width 可以直接写在标签里面也可以写在 style 和 class 里面(看你喜欢喽,一般直接写在标签里用height 和 width)如下
<canvas ref="myCanvas" height="400" width="450" class="canvas-box"></canvas>
以上准备工作做好之后就可以去 mounted 进行绘制辣 我这里是写了一个函数在mounted调用的
const canvas = this.$refs.myCanvas //获取 canvas 组件
const ctx = canvas.getContext('2d') //获取 canvas 绘图上下文
首先拿到 canvas 组件 再通过 getContext
方法创建 canvas 绘图上下文
接下来就可以直接绘制你想要的东西了 这里简单介绍绘制线条和面(描边和填充)
可以设置线条的颜色和宽度 也可以设置填充色
ctx.stroke(x, y, width, height) ctx.fillRect(x, y, width, height)
这两个都有四个参数 x,y 表示距离左上角的距离 width, height 是宽高
//描边绘制矩形
ctx.lineWidth = 5; // 设置线条宽度为5像素
ctx.moveTo(0,0); // 路径绘制命令的起点
ctx.lineTo(350,50); // 路径绘制转折点
ctx.stroke();
ctx.moveTo(50,200);
ctx.lineTo(250,200);
ctx.lineTo(250,350);
ctx.strokeStyle = 'rgb(250,46,5)'//用来设置线条的颜色
ctx.stroke();
//填充绘制矩形
ctx.fillStyle = 'rgb(78,197,17)'
ctx.fillRect(20, 20, 200, 200)
如果你想要设置背景图片的时候
const backgroundImage = new Image() // 创建Image对象
backgroundImage.src = '图片路径' //设置图片路径
backgroundImage.onload = function(){
ctx.drawImage(backgroundImage, 0, 0, canvas.width, canvas.height) //绘制背景图片
}
ctx.drawImage(backgroundImage, x, y, canvas.width, canvas.height)
这里的 x,y 是指背景图片距离左上角的距离 canvas.width canvas.height 可以自行设置大小 如果不设置的话就是图片本来的大小 多余的部分会被裁剪掉
本地图片需要用 require 进行导入 backgroundImage.src = require('@/assets/images/bg.png');
最最最重要的点!!!
如果设置了背景图片后面绘制的内容一定要放在背景图的 onload 函数中否则绘制的内容都会被 这张图片盖住的
具体代码就在下面啦
<template>
<div class="content">
<canvas ref="myCanvas" height="400" width="450"></canvas>
</div>
</template>
<script>
export default {
name: "canvasTest",
mounted() {
this.drawCanvas()
},
methods: {
drawCanvas() {
const canvas = this.$refs.myCanvas //获取 canvas 组件
const ctx = canvas.getContext('2d') //获取 canvas 绘图上下文
const backgroundImage = new Image() // 创建Image对象
backgroundImage.src = 'https://ts1.cn.mm.bing.net/th/id/R-C.66d7b796377883a92aad65b283ef1f84?rik=sQ%2fKoYAcr%2bOwsw&riu=http%3a%2f%2fwww.quazero.com%2fuploads%2fallimg%2f140305%2f1-140305131415.jpg&ehk=Hxl%2fQ9pbEiuuybrGWTEPJOhvrFK9C3vyCcWicooXfNE%3d&risl=&pid=ImgRaw&r=0' //设置图片路径
backgroundImage.onload = function(){
ctx.drawImage(backgroundImage, 0, 0, canvas.width, canvas.height) //绘制背景图片
// 设置线条样式为圆滑转折点和端点
ctx.lineJoin = 'round'; // 设置转折点样式为圆滑
ctx.lineCap = 'round'; // 设置端点样式为圆滑
// 设置线条宽度
ctx.lineWidth = 5; // 设置线条宽度为5像素
ctx.moveTo(0,0); // 路径绘制命令的起点
ctx.lineTo(350,50); // 路径绘制转折点
ctx.stroke();
ctx.moveTo(50,200);
ctx.lineTo(250,200);
ctx.lineTo(250,350);
ctx.lineTo(50,350);
ctx.lineTo(50,200);
ctx.strokeStyle = 'rgb(250,46,5)'
ctx.stroke();
}
}
}
}
</script>
最后的效果