1. fillRect() 简单填充模式的使用 因为canvas是html5的官方标签,不需要额外引入
<!--
id: 表示元素的唯一性
width: 画布的宽度
height:画布的高度
-->
<canvas id="c1" width="600" height="400"
></canvas>
<script>
//1.找到画布
var c11 = document.getElementById("c1");
// 2. 获取画笔,上下文对象
var ctx = c11.getContext("2d");
ctx.fillStyle="#FF0000";
//3. 绘制图形
//3.1 绘制矩形fillRect(位置x,位置y,宽度,高度)
ctx.fillRect(100,200,300,300);
</script>
2.ctx.strokeRect()绘制路径
<!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>
<!--
id: 表示元素的唯一性
width: 画布的宽度
height:画布的高度
-->
<canvas id="c1" width="600" height="400"
></canvas>
<script>
//1.找到画布
var c11 = document.getElementById("c1");
// 2. 获取画笔,上下文对象
var ctx = c11.getContext("2d");
//3. 绘制图形
//3.2 路径绘制矩形
ctx.strokeRect(100,100,200,100);
</script>
</body>
</html>
简单综合使用
<div>
<el-upload
class="upload-demo"
ref="upload"
action="#"
:show-file-list="false"
:before-upload="beforeUpload"
>
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
</div>
<div>
<canvas id="c1" width="600" height="400"></canvas>
</div>
<img id="img1" :src="file" style="width: 100px; height: 100px;"/>
<a :href="hrefdow" download style="display: inline-block;">下载</a>
<script>
//当上传完毕之后触发函数
beforeUpload(file1){
this.uploadFile = file1;
const freader = new FileReader();
//获取文件并将其转换为url
freader.readAsDataURL(file1);
freader.onload = () => {
this.file = freader.result;
//当图片存储之后调用函数填写到canvas
this.imageCavcas(file1);
};
},
imageCavcas(file1){
//1.找到画布
var c11 = document.getElementById("c1");
// 2. 获取画笔,上下文对象
var ctx = c11.getContext("2d");
const img = new Image();
img.src = this.file;
img.onload = () =>{
//图片挂在成功之后载入canvas
ctx.drawImage(img, 0, 0, c11.width, c11.height);
ctx.font="30px Arial";
ctx.strokeText("这是一个水印",10,50);
//从canvas导出
this.hrefdow = c11.toDataURL();
const img1 = document.getElementById("img1");
img1.src = this.hrefdow;
}
},
<script/>